File: common.c

package info (click to toggle)
taper 6.9rb-5
  • links: PTS
  • area: main
  • in suites: woody
  • size: 1,444 kB
  • ctags: 1,604
  • sloc: ansic: 15,921; makefile: 248
file content (2483 lines) | stat: -rw-r--r-- 67,457 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483

/*
   Time-stamp: <00/01/28 17:39:31 yusuf>

   $Id: common.c,v 1.77.2.2 1999/05/12 11:09:17 yusuf Exp $	

*/

#ifndef lint
static char vcid[] = "$Id: common.c,v 1.77.2.2 1999/05/12 11:09:17 yusuf Exp $";
#endif /* lint */



#include "taper.h"

  
_s8 check_selected(_u32 rec)
{
    /* Checks whether rec 'rec' is selected using the memory
       representation

       TRUE if selected, FALSE if not

       */
    
    if ( !((m_files+rec)->unselected) &&
	 ((m_files+rec)->selected))
	return TRUE;
    return FALSE;
}


void clear_ifd()

    /* Clears the ifd structure */
{
    int x;
    
    ifd.magic = INFO_MAGIC;
    for (x=0; x<INFO_INDICIES; x++) {
	ifd.free[x] = 0;
	ifd.end[x] = 0;
	ifd.root[x] = 0;
    }
    ifd.archive_id = 0;				 /* setup info file header */
    ifd.magic = INFO_MAGIC;
    ifd.number_tapes = 0;
    ifd.number_tsi = 0;
    ifd.number_volumes = 0;
    ifd.size_volume_headers = 0;
    ifd.no_in_archive = 0;
    memset(ifd.archive_title, 0, sizeof(ifd.archive_title));
}


void paint_main() {
    my_werase(win_main, COLOR_MAIN); wrefresh(win_main);
}

void init_common_vars()
{
    no_vol_details = 0;
    no_in_archive = 0;
    no_sel = 0;
    no_exclude = 0;
    in_dir = 0;
    total_selected = 0;
    total_compressed = 0;
    total_excluded = 0;
    total_uncompressed = 0;
    dv = 0;
    log_errors = 0;
    log_warnings = 0;
    memset(&tdh, 0, sizeof(tdh));
    memset(&ifd, 0, sizeof(ifd));
    write_pid = 0;
    update_tsi = 0;
}



_errstat make_info_dirs(void)
{
/* Checks to see if info directory exists. If not, it is created 
 * 
 * Returns -1 for error
 *          1 for OK
*/
    
    struct stat buf;
    int  err;
    
    err = stat(taper_info_files, &buf);
    if (err == 0) 				 /* no problems opening */
      return (S_ISDIR(buf.st_mode)) ? 1 : do_exit(ERROR_INFO_ISNT_DIR);
    if (errno != ENOENT)
      return do_exit(ERROR_CREATING_INFO);
    return mkdir(taper_info_files, S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH);
}


void make_stripped_cf(void)
{
    char *s;
    int  l;

    strip_cf = 0;
    if (!*cf) return;				 /* no common, therefore no strip */
    if (!lstrip) return;			 /* no strip */

    s = cf;
    l=1;
    while (l<lstrip) {
	s++;
	while (*s && (*s != '/'))  s++;
	l++;
    }
    strip_cf = s+(*s == '/') - cf;
    
}


_errstat put_in_buf(char **cp, char *s, _s32 *cz)
{
/* Puts the string 's' into the buffer at 'cp'. cz is the running size of buffer */

    _s32 offset;

    offset = *cp - vol_details;
    *cz += strlen(s)+1;
    vol_details = my_realloc(vol_details, *cz);
    if (vol_details == NULL) return -1;
    *cp = vol_details + offset;
    strcpy(*cp, s);
    *cp += strlen(s)+1;
    no_vol_details++;
    return 0;
}


_errstat extract_vol_details(void)
{
/*  Puts the volume details in a buffer for use by on_vol window */

    _s32 c, c1, cz=0;
    char *cp, *xp, s[MAX_FNAME];
    struct volume_header vh;
    struct tm *t;
    _s32  xx;

    no_vol_details=0;
    cp = vol_details;
    xp = (char *) vol_headers;
    for (c=0; c<ifd.number_volumes; c++) {
	*s = 0;
	if (put_in_buf(&cp, s, &cz) == -1) return -1;
	memcpy(&vh, xp, sizeof(struct volume_header));/* to ensure aligned */
	xp += sizeof(struct volume_header);
	if (*vh.volume_title)
	  sprintf(s, "Volume %d %s", c+1, vh.volume_title);
	else
	  sprintf(s, "Volume %d <no title>", c+1);
	if (put_in_buf(&cp, s, &cz) == -1) return -1;
	if (vh.volume_magic == VOLUME_MAGIC_INFO) {
	    sprintf(s, "Contains an info file");
	    if (put_in_buf(&cp, s, &cz) == -1) return -1;
	}
	else {
	    sprintf(s, "Contains %d files.", vh.no_in_volume);
	    if (put_in_buf(&cp, s, &cz) == -1) return -1;
	}
	t = localtime(&vh.backup_time);
	sprintf(s, "Backed up at %04d/%02d/%2d %d:%02d", t->tm_year+1900, t->tm_mon+1, t->tm_mday,
		t->tm_hour, t->tm_min);
	if (put_in_buf(&cp, s, &cz) == -1) return -1;
	for (c1=0; c1<vh.no_sels; c1++) {
	    memcpy(&xx, xp, sizeof(_s32)); xp += sizeof(_s32); /* past count byte */
	    put_in_buf(&cp, xp, &cz);
	    xp += xx;				 /* past string */
	    memcpy(&xx, xp, sizeof(_s32)); xp += sizeof(_s32); /* pass count byte */
	    xp += xx;				 /* past filter */
	}
    }
    return 0;
}

	
_errstat get_statinfo(char *fn, struct stat *b)
{
/* Gets the stat info the filename fn. Returns -1 if error */
    
    if (soft_links) {
	if (stat(fn, b) == -1) {
	  if (errno == ENOENT) {
	      if (lstat(fn, b) == -1)
		return -1;
	  }
	}
	else
	    return -1;
    }
    else {
	if (lstat(fn, b) == -1)
	    return -1;
    }
    return 0;
}


_errstat search_file(char *s, _s32 vol, struct info_file_data *i_data)
{
/* Looks for file 's' in archive - s should be full pathname
   starts search at 'starts' 

   return -1 if error or not found
   
   if vol == 0, then will return address of first
     entry with this name, otherwise looks for volume 

 
 * 
 */
    struct info_file_key i_key;
    int com=TRAVERSE_SEARCH;
    char fn[MAX_FNAME];

    if (!info_fd) return -1;       /* no info file - ie. new archive */
    strcpy(i_data->name, s);
    fill_info_key(*i_data, &i_key);
    i_key.fname_pos = -1; strcpy(blank_fname, s);
    while (1) {
	if (ntraverse(0, &i_key, NULL, &i_data->recnum, com, INFO_NAME) == 2)
	    return  -1;				 /* error traversing */
	com = TRAVERSE_CONTINUE;
	if (read_info_filename(i_key.fname_pos, fn) == -1) return -1;
	if (strcmp(fn, s)) return -1;	 /* didn't find it */
	if (i_key.pos_in_archive == 0) return -1; /* not in archive */
	if (!vol || (abs(i_key.volume) == vol)) {
		if (read_info_rec(i_data->recnum, i_data) == -1)
		    return -1;
		return 0;
	}
    }
}


_errstat find_most_recents()
{
    /* Goes through an archive and works out the location of the
       most recent file for every file.

       Can only handle 10,000 files the same!
       
    */
    struct info_file_key i_key, prev, last;
    struct info_file_data i_data;
    int com=TRAVERSE_TOP;
    _u32 rec;
    int x;
    _u32 prevs[10000];
    _u32 prev_count, c;

    if (!info_fd) return -1;       /* no info file - ie. new archive */
    memset(&i_data, 0, sizeof(i_data));
    fill_info_key(i_data, &i_key);
    prev = i_key;
    last = i_key;
    prev_count = 0;
    while (1) {
	x = ntraverse(0, &i_key, NULL, &rec, com, INFO_NAME);
	if (x == 2)  return -1;		 /* error traversing */
	if (x == 1) {
	    for (c=0; c<prev_count; c++) 
		(m_files+prevs[c])->most_recent = last.recnum;
	    return 0;
	}
	com = TRAVERSE_CONTINUE;
	read_info_rec(i_key.recnum, &i_data);
	if (i_key.pos_in_archive == 0) continue;
	if (prev.fname_pos) {
	    if (strcmp(get_fn1(prev.fname_pos), get_fn2(i_key.fname_pos))) {
		for (c=0; c<prev_count; c++) 
		    (m_files+prevs[c])->most_recent = last.recnum;
		prev = i_key;
		prev_count = 0;
	    }
	}
	else
	    prev = i_key;
	prevs[prev_count] = i_key.recnum;
	prev_count++;
	last = i_key;
    }
    return 0;
}


_errstat file_more_recent(char *s1, struct stat *b)
{
/* Looks to see if s1 (on the hard disk) is more recent than the file
   in the archive. If s1 is not on the archive, then returns 0 or if
   not as recent. s1 should be a full pathname

   If b == NULL, then reads in file info, otherwise, uses what is in b

   returns -1 if error
*/
    struct stat b1;
    struct info_file_data i_data;
    
    if (b == NULL) {
	if (get_statinfo(s1, &b1) == -1)
	  return -1;
    }
    else
      b1 = *b;

    if (search_file(s1, 0, &i_data) == -1) return 1;
    if (b1.st_mtime > i_data.f.mtime)		 /* on disk is more recent */
      return 1;
    return 0;
}


_u8 make4len(char *s)
{
/* Returns the length of s rounded up to the next multiple of 8 bytes 
   I know the function is make4len (and not make8len), but this was initially
   set to 4 bytes (32 bits) for 32 bits machines and then changed for 8 bytes
   (64 bits) for the ALPHA */
    _u8 sl;
    
    sl = strlen(s) + 1  + sizeof(struct file_info);/* make whole thing a multiple of 8 bytes */
    sl = (sl%8) ? 8-sl%8 : 0;
    return strlen(s)+1+sl;
}



dev_t get_file_info(char *file, struct file_info *fi, _s8 chk, struct stat *ob)
{
/* Gets the file info for 'file'

   Returns 0 if error, otherwise returns device number on
 * which file is
 * 
 * If ob==NULL, gets the statinfo, otherwise uses what's at ob
*/
    
    struct stat b, borg;

    if (ob==NULL)  {
	if (get_statinfo(file, &b) == -1) {
	    if (chk) 
	      do_exit(ERROR_GETINFO);
	    return 0;
	}
    }
    else
      b = *ob;

    stat(file, &borg);				 /* get the original */
    fi->checksum = 0;
    fi->act_size = 0;
    fi->dev = b.st_rdev;
    fi->uid = b.st_uid;
    fi->gid = b.st_gid;
    fi->mode = b.st_mode;
    fi->org_mode = borg.st_mode;
    fi->size = b.st_size;
    fi->atime = b.st_atime;
    fi->mtime = b.st_mtime;
    fi->ctime = b.st_ctime;
    fi->backup_time = time(NULL);		 /* backup time */
    fi->name_len = 0;				 /* will be fixed by add_one_file_engine */
    fi->volume = ifd.number_volumes;		 /* show which volume it belongs to */
    fi->pos_in_archive = 0;			 /* initialise */
    return b.st_dev;
}


inline void update_size(struct info_file_data *i_data)
{
    total_compressed +=  sizeof(struct file_info) + i_data->f.name_len;
	total_uncompressed += sizeof(struct file_info) + i_data->f.name_len;
	if (S_ISREG(i_data->f.mode) || S_ISLNK(i_data->f.mode)) {
	    total_compressed += i_data->f.act_size;
	    total_uncompressed += i_data->f.size;
	}
}


void do_calc_strip(int *maxstrip, struct info_file_data *i_data, char *src)
{
/* Routine to Work out common pathname prefix 
 
 * Uses the information in only_vol
 *
*/    
    int     cf1;
    char    *lp;

    if (only_vol) 				 /* we are volume restricted */
	if (abs(i_data->f.volume) != only_vol) return;
    lp = i_data->name; cf1 = 0;
    while (*lp && cf[cf1]) {
	if (*lp != cf[cf1]) {		 /* pathnames differ here */
	    while (cf1) {
		if (cf[cf1] == '/') 
		    break;
		else
		    cf1--;
	    }
	    cf[cf1+1] = 0;			 /* terminate common here */
	    break;
	}
	lp++; cf1++;
    } 
    if (!strcmp(cf, src)) {			 /* filenames are the same */
	if (!*cf) return;
	if (cf[strlen(cf)-1] == '/')
	    cf[strlen(cf)-1] = 0;
	if (strrchr(cf, '/'))
	    *strrchr(cf, '/') = 0;
	else
	    *cf = 0;
    }
}

struct s_dirs {
    char name[MAX_FNAME];
    _u32 size;
    _u32 org_rec;
    _s32 vol;
};

int admd_cmp(void const *key, void const *s)
{
/* Search engine for bsearch called in add_missing dirs */
    struct s_dirs *d = (struct s_dirs *) s;
    struct s_dirs *k = (struct s_dirs *) key;
    int x;

    x = strcmp(k->name, d->name);
    if (x) return x;
    if (abs(k->vol) == abs(d->vol))
      return 0;
    if (abs(k->vol) < abs(d->vol)) 
      return -1;
    return 1;
}


_errstat process_info(WINDOW *mes, int line, _s8 calc_strip)
{
/* Goes through the archive and does several things:

   a. adds missing directories
   b. calculates directory sizes & puts in memory block  (if calc_strip)
   c. puts file sizes into memory block (if calc_strip)
   d. calculates total_compressed & total_uncompressed (if cacl_strip)
   e. finds common path (if calc_strip) and puts it in lstrip
  
   If for example, the user selected the files /x/y/z and /x/y/z1,
   and the common path is /x, directory y is missing so this routine
   would add the y directory.
*/
    _s32 c, no_dirs;
    struct s_dirs *dirs, *s, prev_buf, ss;
    struct info_file_data i_data;
    mode_t mode;
    struct file_info fi;
    char testf[MAX_FNAME], buf1[MAX_FNAME];
    int maxstrip;
    char src[MAX_FNAME], *lp;
    
    if (mes) status_box(mes, "Looking for missing directories", line, FALSE, 1);

    c=0;

    /* Make a list of all directories in the archive */
    dirs = my_malloc(1); no_dirs=0;
    if (dirs==NULL) return do_exit(ERROR_MEMORY);/* allocate memory for directory list */
    for (c=0; c<ifd.no_in_archive; c++) {	 /* loop through looking for directories */
	if (read_info_rec(c, &i_data) == -1)
	    return do_exit(ERROR_READING_INFO);
	mode = i_data.f.mode;
	if (S_ISDIR(mode)) {			 /* if directory, don't need to check */
	    dirs = my_realloc(dirs, (no_dirs+1)*sizeof(struct s_dirs));/* make room for another directory name */
	    if (dirs==NULL) return do_exit(ERROR_MEMORY);
	    s = dirs+no_dirs;
	    strcpy(s->name, i_data.name);
	    s->vol = i_data.f.volume;
	    s->org_rec = c;
	    s->size = 0;
	    if (s->name[strlen(s->name)-1] == '/') 
	      s->name[strlen(s->name)-1] = 0;   /* remove trailing '/' */
	    no_dirs++;
	}
    }
    qsort(dirs, no_dirs, sizeof(struct s_dirs), (_s32 (*)(const void *, const void *)) strcmp);

    if (calc_strip) {
	total_compressed = 0; total_uncompressed = 0;
	if (read_info_rec(0, &i_data) == -1)
	    return do_exit(ERROR_READING_INFO);
	if (S_ISREG(i_data.f.mode)) m_files->size = i_data.f.size;
	strcpy(src, i_data.name);
	if (no_in_archive == 1) {
	    strcpy(cf, "/");
	    maxstrip = 1;
	}
	update_size(&i_data);
	strcpy(cf, i_data.name);
    }

    /* Now go through info file and do things */
    prev_buf.name[0] = 0;
    for (c=0; c<ifd.no_in_archive; c++) {	 /* loop through each file in archive */
	if (read_info_rec(c, &i_data) == -1)
	    return do_exit(ERROR_READING_INFO);
	
	if ((calc_strip) && (c)) {
	    do_calc_strip(&maxstrip, &i_data, src);
	    if (S_ISREG(i_data.f.mode))	(m_files+c)->size = i_data.f.size;
	    update_size(&i_data);
	}
	
	strcpy(testf, i_data.name);
	if (testf[strlen(testf)-1] == '/') 	 /* remove trailing '/' */
	  testf[strlen(testf)-1] = 0;
	if (strrchr(testf, '/') != NULL)	 /* remove filename */
	  *(strrchr(testf, '/')) = 0;		 
	else
	  *testf = 0;

	strcpy(prev_buf.name, testf);	
	prev_buf.vol = i_data.f.volume;
	while (*testf) {
	    strcpy(ss.name, testf);
	    ss.vol = i_data.f.volume;
	    s = bsearch(&ss, dirs, no_dirs, sizeof(struct s_dirs),
		    admd_cmp);
	    if (s != NULL) {			 /* found entry */
		if (!S_ISDIR(i_data.f.mode))/* don't add size of directory */
		  s->size += i_data.f.size;/* update size */
	    }
	    else {				 /* not found */
		strcpy(buf1, testf);
		strcat(buf1, "/");
		if (get_file_info(buf1, &fi, 1, NULL) == 0) {
		    my_free(dirs);
		    return -1;
		}
		fi.volume = -i_data.f.volume;
		if (add_to_info(&fi, buf1, TRUE) == -1)
		    return -1;
		m_files = my_realloc(m_files, (ifd.no_in_archive+1)*
				     sizeof(struct memory_file));
		dirs = my_realloc(dirs, (no_dirs+1)*
				  sizeof(struct s_dirs));/* make room for another directory name */
		if (dirs==NULL) return do_exit(ERROR_MEMORY);
		s = dirs+no_dirs;
		strcpy(s->name, testf); 
		s->vol = i_data.f.volume;
		s->size = 0;
		s->org_rec = ifd.no_in_archive-1;
		no_dirs++;
		qsort(dirs, no_dirs, sizeof(struct s_dirs), (_s32 (*)(const void *, const void*)) strcmp);   /* resort after addition */
	    }
	    if (strrchr(testf, '/') != NULL)	 /* now take off directory */
	      *(strrchr(testf, '/')) = 0;
	    else
	      *testf = 0;
	}
    }
    if (calc_strip) {
	for (c=0; c<no_dirs; c++)
	    (m_files+(dirs+c)->org_rec)->size =(dirs+c)->size;

	/* Fix up strip stuff */
	if (cf[strlen(cf)-1] != '/')
	    strcat(cf, "/");
	maxstrip = 0;
	lp = cf;
	while (*lp) {
	    if (*lp == '/') maxstrip++;
	    lp++;
	}
	lstrip = maxstrip;
    }
    my_free(dirs);				 /* free up memory */
    return 0;
}


_errstat do_read_vol_dir(_u32 archive_id, char *tape, int mode, _s8 rvdir, _s8 must_exist, _s8 open_recnum) {
/* Closes the backup device after use

   If archive_id == -1, then tries to read the current tape for info file to read.
   If archive_id != -1, then reads the info file associated with this archive

 * If must_exist == FALSE, then if a taper archive is found, the user
 * if prompted whether s/he wishes to append or overwrite
 */    
    WINDOW  *mes=NULL;
    int    fd, err, ofd=0;
    char   tmpf[MAX_FNAME];
    struct info_file_header ifd1;

    total_compressed = 0; total_uncompressed = 0;/* now extract info from info file */
    if (!no_windows)
      mes = status_box(mes, "Rewinding tape", 1, TRUE, 1);
    if (archive_id == -1) {
	err = get_tape_header(mes, 1, &tdh, O_RDONLY);
	tape_close();
	if (err == -1) {close_statusbox(mes); return -1;} 
	if ((err == TAPE_EXIST) & (!must_exist)) {
	    if (!no_windows) {
		append = message_box("Taper archive found", MB_APPENDOVERWRITE);
		touchwin(mes); wrefresh(mes);	 /* update screen */
	    }
	    rvdir = append;
		
	}
	if (!rvdir) {close_statusbox(mes); return err;}  /* don't want to read vol dir */
	if (err != TAPE_EXIST) {close_statusbox(mes); return err;}
    }
    else
      tdh.archive_id = archive_id;

    if (mes)
      mes = status_box(mes, "Opening/Uncompressing info file", 1, FALSE, 1);
    if ((fd = open_info_file(TRUE, tdh.archive_id, open_recnum)) == -1) {
	close_statusbox(mes);
	return -1;
    }
    read(info_fd, (char *) &ifd1, sizeof(struct info_file_header));
    ifd_endianize2mach(&ifd1, &ifd);
    if (ifd.archive_id != tdh.archive_id) {	 /* archive and info files */
	do_exit(ERROR_INFO_MISMATCH);
	goto err;
    }
    if (ifd.magic != INFO_MAGIC)  {
	if (ifd.archive_id == tdh.archive_id) 	 /* must be old format of info file */
	  do_exit(ERROR_INFO_OLD);
	else
	  do_exit(ERROR_INFO_MAGIC);
	goto err;
    }

    /* Allocate memory for various structures */
    m_files = my_realloc(m_files, (1+ifd.no_in_archive)*sizeof(struct memory_file));
    memset(m_files, 0, ifd.no_in_archive*sizeof(struct memory_file));
    vol_headers = my_realloc(vol_headers, ifd.size_volume_headers);
    if (vol_headers == NULL) {
	do_exit(ERROR_MEMORY);
	goto err;
    }
    vt_info = my_realloc(vt_info, sizeof(struct volume_tape_info)*ifd.number_volumes);
    if (vt_info==NULL) {			 /* get block for volume/tape info */
	do_exit(ERROR_MEMORY);
	goto err;
    }
    if (ifd.number_tsi) {
	tsi = my_realloc(tsi, sizeof(struct tape_size_info) * ifd.number_tsi);
	if (tsi == NULL) {
	    do_exit(ERROR_MEMORY);
	    goto err;
	}
    }
    if (read_volume_info(fd) == -1) goto err;	 /* read in the stuff */

    no_in_archive = ifd.no_in_archive;
    if (process_info(mes, 1, TRUE) == -1) goto err; /* adds missing dirs etc.. */
    lstrip = min(lstrip, ostrip);
    make_stripped_cf();				 /* work out position for strip level */
    
    if (find_most_recents() == -1) goto err;	 /* find most recent files */
    
    if (mes)
      status_box(mes, "Extracting volume information", 1, FALSE, 1);
    if (extract_vol_details() == -1) goto err;
    
    if (mes) close_statusbox(mes);
    if (fd) close(fd);
    if (ofd) unlink(tmpf);
    return TAPE_EXIST;

    err:;
      if (mes) close_statusbox(mes);
      if (fd) close(fd);
      if (ofd) unlink(tmpf);
      return -1;
}


char *convtime(char *s, time_t t1, time_t t2)
{
    _s32   secs=t2-t1;
    int    hr,min,sc;
    
    hr=secs/3600;
    min=(secs-hr*3600)/60;
    sc=secs-hr*3600-min*60;
    sprintf(s,"%d:%02d:%02d",abs(hr),abs(min),abs(sc));
    return s;
}

_errstat check_device_names()
{
    char s[MAX_FNAME];
    
/* Converts the device name to a full pathname
   Also checks that block size is properly set */

    if (strchr(ntape, ':') == NULL)		 /* don't prefix if using */
	if (*ntape != '/') {			 /* remote device */
	    sprintf(s, "%s/%s", original_cur_dir, ntape);
	    strcpy(ntape, s);
	}
    if (strchr(tape, ':') == NULL)		 /* don't prefix if using */
	if (*tape != '/') {			 /* remote device */
	    sprintf(s, "%s/%s", original_cur_dir, tape);
	    strcpy(tape, s);
	}
    if (block_size < 2048) {
	(no_windows) ? fprintf(stderr, "Block size is too low. Minimum of 2K needed") :
	               message_box("Block size is too low. Minimum of 2K needed", MB_OK);
	return -1;
    }
    if (block_size > DOUBLE_BUFFER_SIZE) {
	(no_windows) ? fprintf(stderr, "Block size can't exceed DOUBLE_BUFFER size") :
	               message_box("Block size can't exceed DOUBLE_BUFFER size", MB_OK);
	return -1;
	
    }
    return 0;
}


_s32 calc_checksum(int fd)
{
/* Calculates a file checksum 
   Returns -1 if error 
 */
    _s32    sz, chk=0, c;
    
    lseek(fd, 0, SEEK_SET);
    while (1) {
	sz = read(fd, (char *) tr_buffer, max_tr_size);/* read in file */
	if (!sz)				 /* ?EOF */
	  break;
	if (sz == -1) return -1;
	for (c=0; c<sz;c++)			 /* add up bytes in */
	  chk += *(tr_buffer+c);		 /* this file */
    }
    lseek(fd, 0, SEEK_SET);			 /* move back to BOF */
    return labs(chk);				 /* return checksum */
}
    
_s32 mem_calc_checksum(char *m, _s32 sz)
{
/* Calculates the checksum of a memory block 'm' of size 'sz'
   Returns -1 if error */
    _s32    chk=0, c;
    
    for (c=0; c<sz;c++)				 /* add up bytes in */
      chk += *(m+c);				 /* this file */
    return chk;					 /* return checksum */
}


_errstat open_logfile(char *prog)
{
    char s[100];
    
    lf = 0;
    log_errors=0;
    log_warnings=0;
    if ((*log_file) && (log_level)) {
	lf = open(log_file, O_RDWR|O_CREAT|O_APPEND, S_IREAD|S_IWRITE);
	if (lf==-1) {lf=0; return do_exit(ERROR_OPENING_LOG);}
	strcpy(s, "Starting "); strcat(s, prog); strcat(s, " v"); strcat(s, CUR_VERSION);
	write_log(s);
    }
    return 0;
}


void close_logfile(char *prog)
{
    struct stat b;
    char  tmpf[MAX_FNAME], s[MAX_FNAME];
    WINDOW *mes=NULL;
    int    tmpfd;
    
    if (lf) {
	fsync(lf);
	if (fstat(lf, &b) != -1) {		 /* check to ensure size not */
	    if ((b.st_size > log_file_size * 1024*1024) &&
	       (log_file_size)) {		 /* log file too big */
		if (!no_windows) {
		    touchwin(win_main); wrefresh(win_main);
		    mes = status_box(mes, "Log file too big - making smaller", 1, TRUE, 1);
		}
		if (log_level > 2) write_log("Log file is too big - making it smaller");
		lseek(lf, b.st_size - (log_file_size*1024*1024), SEEK_SET);
		taper_tmpnam(tmpf);
		tmpfd = open(tmpf, O_RDWR|O_CREAT|O_APPEND, S_IREAD|S_IWRITE);
		if (tmpfd == -1) {
		    if (log_level > 2) write_log("Unable to open temp file in making log file smaller");
		    goto convclose;
		}
		if (my_filecopy(lf, tmpfd) == -1) {
		    close(tmpfd);
		    unlink(tmpf);
		    if (log_level > 2) write_log("Unable to write in making smaller log file");
		    goto convclose;
		}
		close(lf);			 /* close org log file */
		unlink(log_file);		 /* and remove it */
		lf = tmpfd;			 /* this info goes to the temp file */
		sprintf(s, "%s finished.", prog);
		write_log(s);
		write(lf, "\n\n", strlen("\n\n"));
		close(tmpfd);			 /* close temp file */
		lf = 0;
		my_rename(tmpf, log_file);	 /* rename it to log file */
		if (mes) close_statusbox(mes);
		return;
	    }
	}
	convclose:;
	  lseek(lf, 0, SEEK_END);			 /* move to end of file */
	  sprintf(s, "%s finished.", prog);	 /* to write this info */
	  write_log(s);
	  write(lf, "\n\n", strlen("\n\n"));
	  close(lf);				 /* close log file */
	  lf = 0;
	  if (mes) close_statusbox(mes);
    }
}

    
void calc_tape_pos(_s32 vol_no, _s32 *tape, _s32 *pos)
{
/* Works out on what tape and at what position on the tape
 * vol_no is.  
*/ 
    _s32 count;
    struct volume_tape_info *vti;
    
    vti = (struct volume_tape_info *) vt_info;
    for (count=0; count < ifd.number_volumes; count++)/* find which tape it's on */
	if (vti->volume == vol_no) {		 /* found this volume */
	    *tape = vti->start_tape;
	    break;
	}
        else
          vti++;

    vti = vt_info;
    *pos = (*tape == 1) ? 0 : 1;
    for (count=0; count < ifd.number_volumes; count++) {   /* now find out how many volumes are before it */
	if ((vti->start_tape == *tape) && (vti->volume < vol_no))
	  (*pos)++;
	vti++;
    }
}


char *get_vh(struct volume_header *svh, _s32 vol)
{
/* Works out where volume header for volume 'vol' is
 * assuming the volume headerse start at svh */
    
    _s32 c=0, c1, x;
    char *s = (char *) svh;
    struct volume_header v;
    
    while (c<vol-1) {
	memcpy(&v, s, sizeof(struct volume_header));   /* to ensure struct aligned */
	s += sizeof(struct volume_header);	 /* past volume header */
	for (c1=0; c1<v.no_sels;c1++) {	 /* past entries */
	    memcpy(&x, s, sizeof(_s32));
	    s += x + sizeof(_s32);	 /* entry */
	    memcpy(&x, s, sizeof(_s32));
	    s += x + sizeof(_s32);	 /* filter */
	}
	c++;
    }
    return s;
}


_errstat traverse_volume(file_passed_action action, _s32 no_in_vol,
		    time_t t_start, WINDOW *mes_box, _s8 full_traverse,
		    print_status ps, _s32 *cur_in_vol,
		    _s8 use_info, chksum_err ce)
/* Traverses a volume.
 * Returns -1 is user aborted, 0 if finished mid-way, 1 if fully finished
 * 
 * If full_traverse == 1, then traverse completes the volume
 * otherwise, traverse is allowed to finish mid-volume
 * 
 * If use_info == TRUE, then the file_info & filename is obtained
 * from the info file rather than from the tape. The tape file_info
 * is read, and only the fi.pos_in_vol is used to obtain the correct
 * entry in the info file
 * 
 * Action should return
 *    -4 to stop traverse even if full traverse on
 *    -3 to stop traverse - file NOT read] should stop 
 *    -2 to stop traverse - file read    ] should stop
 *    -1 error - abort                   ] 
 *     0 file was not read in
 *     1 file was read in
 *
 * if no_in_vol == -1, then continue ad infinitum
 *
 * chksum_err should return
 *     0 to continue traverse
 *    -1 to stop
 * 
 *   if chksum wants traverse to stop, traverse will return 0
 */ 
{
    _s32 tr, x, sz, a;
    struct file_info fi;
    char fn[MAX_FNAME],  scr[100+MAX_FNAME];
    char l[MAX_FNAME*2];
    time_t t_current;
    _s32  chk, info_pos=0;
    struct info_file_data i_data;

    *cur_in_vol=0;
    while ((*cur_in_vol < no_in_vol) || (no_in_vol == -1)) {
	*scr = wgetch(mes_box);
	if ((*scr == 'q') || (*scr == 'Q')) {
	    if (message_box("Confirm abort", MB_YESNO))   /* check user wants to abort */
	      return -1;
	    touchwin(mes_box); wrefresh(mes_box);
	}
	(*cur_in_vol)++;				
	sprintf(l, "Reading in file info & filename");
	if (tape_read_fi(&fi) == -1) return -1;
	if (use_info) {				 /* find which info file */
	    while (info_pos < no_in_archive) { /* look for this file in volume dir */
		if (read_info_rec(info_pos, &i_data) == -1)
		    return do_exit(ERROR_INFO_FILE);
		if (fi.pos_in_archive == i_data.f.pos_in_archive)
		  break;
		info_pos++;
	    }
	    if (info_pos > no_in_archive)	 /* couldn't find it for */
	      return do_exit(ERROR_INFO_FILE);	 /* some reason */
	    fi = i_data.f;
	}
	if (fi.checksum == -2) {
	    if (old_archive) {
		if (log_level > 2) write_log("Negative 2 checksum detected from old version of taper - corrected");
		fi.checksum = 2;
	    }
	    else {
		write_log("Previously aborted backup detected");
		break;
	    }
	}
	if (fi.checksum < 0) 
	  if ((fi.checksum != -1) && (fi.checksum != -2)) {
	      fi.checksum = labs(fi.checksum);
	      if (log_level > 2) write_log("Negative checksum detected from old version of taper - corrected");
	  }
	if ((fi.name_len == 0) || (fi.act_size == -1)) {/* need to check due to bug in earlier tapers */
	    write_log("Incorrect file count in volume. Fudged to overcome");   /* and also aborted backups */
	    break;				 /* assume that this is now EOF */
	}
	if (tape_read(fn, fi.name_len) != fi.name_len) /* skip past filename */
	  return -1;
	if (use_info) 				 /* use filename from */
	    strcpy(fn, i_data.name);		 /* info file */
	t_current = time(NULL);

	if (ps) {				 
	    touchwin(mes_box);			 /* don't know when read may have hit end of tape */
	    ps(mes_box,  *cur_in_vol, no_in_vol, abs(fi.volume), fi.act_size, fn,
	     t_start, t_current);			 /* let caller print status box */
	}
	a = (action == NULL) ? 0 : action(&fi, fn, &i_data);
	if (a==-1) return -1;			 /* error */
	if ((a == -2) && (!full_traverse)) 
	  return (*cur_in_vol == no_in_vol);	 /* finish traverse */
	if ((a == -3) && (!full_traverse)) 
	  return (*cur_in_vol == no_in_vol);	 /* finish traverse */
	if (a==-4) return 0;			 /* unconditional finish */
	if ((a==1) || (a==-2))  continue;	 /* file was read in */

	if (fi.checksum == -1) continue;
	if ((!old_archive) && (fi.checksum == -2)) continue;

	sprintf(l, "Passing file %s", fn);
	if (log_level > 1) write_log(l);
	if (S_ISLNK(fi.mode)) {
	    sprintf(l, "Passing link info for %s", fn);
	    if (log_level > 2) write_log(l);
	    if (tape_read_namelen(fn) == -1) return -1;
	    continue;
	}

	if (!S_ISREG(fi.mode)) {		 /* if not regular file, checksum should be 0 */
	    chk = 0;
	    goto chkchksum;
	}

	sz = fi.act_size;			 /* otherwise, assume regular file */
	chk = 0;
	while (1) {				 /* copy file accross */
	    tr = min(sz, max_tr_size); 
	    x = tape_read(tr_buffer, tr);	 /* to device file   */
	    if (!x) break;
	    if (x == -1) 
	      return -1;
	    chk += mem_calc_checksum(tr_buffer, x);
	    sz -= x;
	    if (!sz) break;			 /* read all we need to */
	}
	
      chkchksum:;
	if (labs(chk) != fi.checksum) {
	    sprintf(l, "ERROR:  Checksum error for file %s", fn);
	    write_log(l);
	    log_errors++;
	    if (ce != NULL) {			 /* checksum error handler */
		if (ce(&fi, fn) == -1) 
		    return 0;
		touchwin(mes_box); wrefresh(mes_box);
	    }
	}
	else {
	    sprintf(l, "Checksum OK for file %s", fn);
	    if (log_level > 1) write_log(l);
	}
    }
    return 1;					 /* successful return */
}


void final_message(char *prog)
{
/* Prints the final message, telling how many warnings & how many
 * errors were encountered
 */
    
    char s[4][150];

#ifndef TRIPLE_BUFFER				 /* if not using triple buffering */
    if (!strcmp(prog, "Restore"))  {		 /* ie. not using SYSV_IPC shared memory */
	log_warnings=-1;			 /* these won't have been updated */
	log_errors=-1;
    }
#endif    
    if (no_windows) return;
    my_werase(win_main, COLOR_MAIN); wrefresh(win_main);
    sprintf(s[0], "%s completed", prog);
    strcpy(s[1], "");
    sprintf(s[2], "%d Warnings", log_warnings);
    sprintf(s[3], "%d Errors", log_errors);
    multi_message_box(s, 4, MB_OK, TRUE);
}


void print_title_line()
{
/* Prints the top title line with the archive ID & archive title */
    char s[200];

    if (no_windows) return;
    my_werase(title, COLOR_TITLE);
    if (*ifd.archive_title)
      sprintf(s, "Archive ID %u. Title '%s'", ifd.archive_id, ifd.archive_title);
    else
      sprintf(s, "Archive ID %u. Title <no title>", ifd.archive_id);
    centre(title, 0, s, COLOR_TITLE);
    wrefresh(title);
}


void backrest_paint(void) {
    touchwin(title); touchwin(files); touchwin(selection); touchwin(exclude); touchwin(on_vol); 
    wrefresh(title); wrefresh(files); wrefresh(selection); wrefresh(exclude); wrefresh(on_vol); 
}


_errstat bmessage_box(char *s, int type) {
    int x=message_box(s, type);
    backrest_paint();
    return x;
}


void backrest_init_windows(void) {				 
/*  Initialise windows and print screen edges etc..      */

    int       top_right_startx, btm_right_startx;
    
    screen_xlen=win_main->_maxx+1;		 /* Dimensions of screen */
    screen_ylen=win_main->_maxy+1;
    
    screen_ylen_files = screen_ylen/2 + 3;
    screen_ylen_selection = screen_ylen - screen_ylen_files;
    top_left_width = screen_xlen*6/10;		 /* split 60% */
    top_right_width = screen_xlen-top_left_width;	 
    top_right_startx = top_left_width;
    btm_left_width = screen_xlen*5/10;		 /* split 50% */
    btm_right_width = screen_xlen-btm_left_width;	 
    btm_right_startx = btm_left_width;
    
    files = my_newwin(screen_ylen_files, top_left_width,
		  1, 0);			 /* files hand window */
    on_vol = my_newwin(screen_ylen_files, top_right_width,
		  1, top_right_startx);		 /* on volume window */
    selection = my_newwin(screen_ylen_selection, btm_left_width,/* selection window */
		   screen_ylen_files+1, 0);
    exclude = my_newwin(screen_ylen_selection, btm_right_width,
			    screen_ylen_files+1, btm_right_startx);
    keypad(on_vol, TRUE); 			 
    keypad(selection, TRUE);
    keypad(exclude, TRUE);
    keypad(files, TRUE);			 /* set input modes */
}



void backrest_clear_screen(void)
{
    my_werase(on_vol, COLOR_ONVOL); my_werase(files, COLOR_DIRECTORY); 
    my_werase(selection, COLOR_SELECTED);  my_werase(exclude, COLOR_EXCLUDED);
    box(on_vol, ACS_VLINE, ACS_HLINE);
    box(files, ACS_VLINE, ACS_HLINE);		 /* draw boxes around */
    box(selection, ACS_VLINE, ACS_HLINE);	 /* screens */
    box(exclude, ACS_VLINE, ACS_HLINE);
    wrefresh(on_vol); wrefresh(files); wrefresh(selection); wrefresh(exclude);
}


void backrest_kill_windows(void)
{
    if (no_windows) return;
    my_delwin(on_vol);
    my_delwin(selection);
    my_delwin(files);
    my_delwin(exclude);
    my_werase(win_main, COLOR_MAIN);
    wrefresh(win_main);
}

void backrest_free_memory(void)
{
    my_free(sb_directory);
    my_free(directory);
    my_free(dirs);
    my_free(sel_files);
    my_free(excluded_files);
    my_free(vt_info);
    my_free(tsi);
    my_free(vol_headers);
    my_free(vol_details);
    my_free(m_files);
}


_errstat backrest_do_mallocs(void)
{
/* Allocates memory for backup stuff */

    sb_directory = my_malloc(1);
    directory = my_malloc(1);
    dirs = my_malloc(1);
    sel_files = my_malloc(sizeof(*sel_files));
    excluded_files = my_malloc(sizeof(*excluded_files));
    vt_info = my_malloc(1);
    tsi = my_malloc(1);
    vol_headers = my_malloc(sizeof(int));
    vol_details = my_malloc(1);
    m_files = my_malloc(1);
    if ((dirs == NULL) || (sel_files == NULL) || (vt_info == NULL) ||
	(vol_headers == NULL) || (m_files == NULL)
	|| (directory == NULL) || (vol_details == NULL) || (tsi == NULL) ||
	(sb_directory == NULL) || (excluded_files == NULL))
      return -1;
    return 0;
}
    

void print_on_voldir_line(WINDOW *win, _s32 entry, int line, char ref) {
/*  Prints one entry in a directory at line 'line'  */

    _s32 c=0;
    char *s;
    static char spc[] = {"                                                                                                                                                      "};
    char s1[MAX_FNAME], s2[MAX_FNAME];
    
    s = vol_details;				 /* find appropriate */
    while (c++<entry)				 /* line in vol_details buffer */
      while (*s++);

    if (!strncmp(s, "Volume ", strlen("Volume ")) ||
	!strncmp(s, "Contains ", strlen("Contains ")) ||
	!strncmp(s, "Backed up at ", strlen("Backed up at ")) )
      mvwaddstr(win, line+1, 2, s);
    else {
	strcpy(s1, &s[(*s == '!')]);
	pr_filename(s1, s2, win->_maxx-6);
	if (*s == '!') {
	    mvwaddstr(win, line+1, 4, "(");
	    strcat(s2, ")");
	}
	mvwaddstr(win, line+1, 5, s2);		 
    }
    if (!*s) {					 /* blank line */
	spc[win->_maxx-2] = 0;
	mvwaddstr(win, line+1, 1, spc);
    }
    centre(bottom, 0, s, COLOR_BOTTOM); wrefresh(bottom);
    if (ref)
      wrefresh(win);
}


void print_on_vol_dir(WINDOW *win, _s32 start, char *p_scroll) {
    int    cur_line=1, cur_ent;
    char   s[100];
    
    my_werase(win, COLOR_ONVOL);
    sprintf(s, "On archive");
    s[win->_maxx-1] = 0;
    wattron(win, A_UNDERLINE);
    mvwaddstr(win, 1, 1, s);
    convert(s, total_compressed);
    mvwaddstr(win, 1, win->_maxx-strlen(s)-1, s);
    wattroff(win, A_UNDERLINE);
    cur_ent = start;
    if (no_vol_details)
      while (cur_line < screen_ylen_files-2) {
	  print_on_voldir_line(win, cur_ent, cur_line, FALSE);/* print line */
	  cur_line++;			 /* increment */
	  cur_ent++;
	  if (start+cur_line > no_vol_details) /* check that not at end of dir */
		break;
      }
    *p_scroll = 0;
    print_scroll_bar(win, no_vol_details, &vol_sd, win->_maxy,
		     win->_maxx, p_scroll);
    wrefresh(win);
}


void print_my_name()
{
    char s[100];
    
    if (no_windows) return;
    sprintf(s, "Taper %s by Yusuf Nagree (yusuf@e-survey.net.au)", CUR_VERSION);
    centre(bottom, 0, s, COLOR_BOTTOM);
    wrefresh(bottom);
}


char backrest_mfn(struct direntry *x, char *dir_name, char *prefix)
{
    char t[MAX_FNAME];
    
    strcpy(t, "Set ");
    strcat(t, &x->entry.d_name[strlen(prefix)]);
    strcpy(x->entry.d_name, t);
    return TRUE;
}


FILE *backrest_restore_backupset(char *nm)
{
/* Opens a file set. 
 * 
 * If nm == NULL, user is prompted for backup file set name,
 * otherwise, use nm as filename
 * 
 * Returns File handle of NULL if couldn't */
    FILE *f;
    char s[MAX_FNAME], s1[MAX_FNAME];
      
    if (nm != NULL) {
	strcpy(s, "Set ");
	strcat(s, nm);
    }
    else
      select_file(taper_info_files, "taper_set.", s, backrest_mfn, TRUE);
    strcpy(s1, dir_cur_dir); strcat(s1, "/taper_set."); 
    strcat(s1, &s[4]);
    f=fopen(s1, "r");
    if (f==NULL) 
	do_exit(ERROR_OPENING_SET);
    return f;
}
    

void backrest_save_backupset(int in_backup)
{
/* Save file set */
    char s[MAX_FNAME], s1[MAX_FNAME];
    FILE *f;
    struct selected_entry *se=sel_files;
    int c;
    
    *s =0;
    if (!get_string(win_main, s, MAX_FNAME, "Enter name to give set"))
      return;
    if (!*s) return;
    strcpy(s1, taper_info_files);
    strcat(s1, "/"); strcat(s1, "taper_set."); strcat(s1, s);
    if (make_info_dirs() == -1)			 /* make directories */
      return;
    f = fopen(s1, "r+");
    if (f!=NULL) {
	fclose(f);
	if (bmessage_box("File set exists", MB_APPENDOVERWRITE))
	  f = fopen(s1, "a");
	else
	  f = fopen(s1, "w");
    }
    else
      f = fopen(s1, "w");
    if (f==NULL) {
	do_exit(ERROR_CREATING_SET);
	return;
    }
    for (c=0; c<no_sel; c++) {
	fprintf(f, "I\n");
	fprintf(f, "%s\n", se->i.name);
	fprintf(f, "\n");
	se++;
    }
    se = excluded_files;
    for (c=0; c<no_exclude; c++) {
	fprintf(f, "E\n");
	fprintf(f, "%s\n", se->i.name);
	fprintf(f, "\n");
	se++;
    }
    fclose(f);
}


_errstat exclude_dir(char *fn)  
{
/* Sees if directory 'fn' should be excluded */
    
    char *s, *b, tok[MAX_FNAME];
    int fin=0;
    
    if (!*exclude_dirs) return 0;		 /* empty exclusion list */ 
    strcpy(tok, exclude_dirs);
    s=tok;
    while (!fin) {
	b=s;
	while (*s && (*s != ' ')) s++;		 /* look for space or eos */
	if (!*s) fin=1;				 /* end of string */
	*s = 0; 
	if (strlen(b) <= strlen(fn))		 /* b is excluding directory */
	  if (!strncmp(b, fn , strlen(b)))
	      return 1;
	s++;
    }
    return 0;
}


_errstat exclude_archive(char *fn)
{
/* Determines whether to exclude file 'fn' from archive 
 * 
 * returns 1 if should be excluded (ie. in list)
 * returns 0 if shouldn't be excluded
*/
    if (exclude_list(fn, exclude_files) == 1)	 /* remove on basis of suffix */
      return 1;
    if (exclude_dir(fn)) return 1;
    return 0;
}

    
_errstat process_dir(WINDOW *mes, int ln, char *org_dir, char inc, 
		 do_process_dir dpd, _s8 send_dir)
{
/* Goes through the directory given full dir and calls the
 * function dpd with each entry. If send_dir=TRUE, then
 * directory entries are also sent to dpd, otherwise they
 * are not
 * 
 * If org dir is a file, then just does one dpd and returns
 * 
 * The dpd function should return 0 to continue,
 * -1 to stop the process_dir
 * 
 * Returns -1 if user aborted. Errors are ignored - the sizing continues

 * Ignores: log file
            backup file if a file rather than device
	    info file corresponding to archive
*/

    char  *dir_list=NULL;
    _s32  len=0;
    DIR  *dir_ptr;
    struct dirent *x;
    struct stat b;
    char   s1[MAX_FNAME], old_dir[MAX_FNAME], cur_dir[MAX_FNAME];
    char   ifnb[MAX_FNAME], ifn[MAX_FNAME];
    int    app;
    char   s, z;
    dev_t  cur_fs=0;

    if (get_statinfo(org_dir, &b) != -1) {/* get file information */
	cur_fs = b.st_dev;
	if (!S_ISDIR(b.st_mode)) {		 /* if org_dir not a directory then do the dpd and finish*/
	    if (!exclude_archive(org_dir)) {	 /* not on exclude list */
		if (inc) {
		    if (file_more_recent(org_dir, &b)) {
			dpd(org_dir, &b);
		    }
		}
		else {
		    dpd(org_dir, &b);
		}
	    }
	    return 0;				 /* don't bother with rest */
	}
    }
    
    make_info_filename(ifnb, tdh.archive_id);
    dir_list = my_malloc(100*MAX_FNAME);
    if (S_ISDIR(b.st_mode)) {			 
	if (send_dir)
	    if (dpd(org_dir, &b) == -1) goto finish;
	if (exclude_dir(org_dir)) return 0;	 /* exclude this directory */
    }
    
    getcwd(old_dir, sizeof(old_dir));		 /* save old directory */
    strcpy(cur_dir, org_dir);
    
    if (mes) nodelay(mes, TRUE);
    while (1) {
	if (mes) {
	    s = wgetch(mes);
	    if ((s == 'q') || (s == 'Q'))
	      return -1;
	    status_box(mes, cur_dir, ln, FALSE, 1);
	}
	chdir(cur_dir);
	if ((dir_ptr = opendir(cur_dir)) == NULL)/* can't open directory */
	  goto nextdir;
	app = !(cur_dir[strlen(cur_dir)-1] == '/');   /* do we need to append '/'? */
	while (1) {				 /* process directory */
	    x=readdir(dir_ptr);
	    if (x==NULL) break;			 /* end of directory */
	    if (get_statinfo(x->d_name, &b) == -1)/* get file information */
	      continue;				 /* couldn't - ignore file */
	    if (!S_ISDIR(b.st_mode)) {
		if ((proc_dev) && (proc_dev == b.st_dev))/* is the /proc directory */
		    continue;
		if ((ofs) && (cur_fs != b.st_dev))	 /* this directory is not on same filesystem */
		    continue;
	    }
	    strcpy(s1, cur_dir);
	    if (app) strcat(s1, "/");
	    strcat(s1, x->d_name);
	    if (dv) 
	      if (is_regfile(dv))		 /* if backup device is a reg file */
	        if (!strcmp(s1, tape) || !strcmp(s1, ntape))/* don't backup backup device */
	          continue;
	    if (!strcmp(s1, log_file))		 /* don't back up log file */
	      continue;
	    if (!strcmp(s1, ifnb))		 /* check info files */
		continue;
	    for (z=0; z<=INFO_INDICIES; z++) {
		sprintf(ifn, "%s.%d", ifnb, z);
		if (!strcmp(s1, ifnb))
		    break;
	    }
	    if (z<=INFO_INDICIES) continue;
	    if (S_ISDIR(b.st_mode)) {
		if (!strcmp(x->d_name, "."))	 /* don't worry about these */
		  continue;
		if (!strcmp(x->d_name, ".."))
		  continue;
		if ((proc_dev) && (proc_dev == b.st_dev))/* is the /proc directory */
		    continue;
		if ((ofs) && (cur_fs != b.st_dev))	 /* this directory is not on same filesystem */
		    continue;
		if (!( (exclude_dir(s1)) ||	 /* if on exclude list   OR */
		     ((ofs) && (cur_fs != b.st_dev)) || /* /proc directory  OR */
		     ((proc_dev) && (proc_dev == b.st_dev)) )) { /* different filesystem */
		    len++;			 /* don't add to list of directories we must process */
		    if (len%100 == 0) 
		      dir_list = my_realloc(dir_list, (len+99)*MAX_FNAME);
		    strcpy((dir_list+(len-1)*MAX_FNAME), s1);
		}
	    }
	    if (!S_ISDIR(b.st_mode) || ((S_ISDIR(b.st_mode) && send_dir))) {
		if ( (!exclude_archive(s1)) ||
		     ((exclude_archive(s1) && (S_ISDIR(b.st_mode)))) ) {
		    if (inc) {
			if (file_more_recent(s1, &b)) {
			    if (dpd(s1, &b) == -1) goto finish;
			}
		    }
		    else {
			if (dpd(s1, &b) == -1) goto finish;
		    }
		}
	    }
	}					 /* finished processing directory */
	nextdir:;
	if (dir_ptr) closedir(dir_ptr);
	if (!len) break;			 /* finished */
	len--;
	strcpy(cur_dir, dir_list+len*MAX_FNAME);
    }

    finish:;
    chdir(old_dir);				 /* change back to old directory */
    my_free(dir_list);
    if (mes) nodelay(mes, FALSE);
    return 0;
}


#ifdef TRIPLE_BUFFER
_errstat make_shm_block(int *id, _s32 blksize, _s8 **shm)
{
/* Makes a shared memory block. 
   Returns 0 if OK, -1 if not */
    int lp=0;
    
    while (1) {					 /* shared memory */
	*id = shmget(IPC_PRIVATE, blksize, IPC_CREAT|IPC_EXCL|0666);
	if (*id != -1) break;			 /* made it OK */
	lp++;
	if (lp==100)				 /* only allow 100 goes */
	  return do_exit(ERROR_SETTING_SHARED_MEM);
    }					 

    *shm = (_s8 *) shmat(*id, 0, 0);		 /* try and attach memory */
    if (*shm == (_s8 *) -1) 
	return do_exit(ERROR_SETTING_SHARED_MEM);
    return 0;
}
#endif


_errstat init_buffers(_s8 reall)
{						 
/* Allocates memory for three buffers
 * 
 * 1. Read buffer
 * 2. Write buffer
 * 3. File transfer buffer
 * 
 * If reall = 1, then buffers are realloced, otherwise they
 * are malloced
 * 
 * Note: There will be problems if you are downsizing the buffer and
 *   you have data left in the write_buffer

 These do NOT go through my_malloc, because I know about them and they
 will be be deleted. If they went through my_malloc, they would have to be
 reallocated & deallocated after every call to a subsystem
 */ 
    read_buffer = (reall == 1) ? realloc(read_buffer, block_size) : malloc(block_size);
    if (read_buffer == NULL) goto err;
    if (!reall) {
#ifdef TRIPLE_BUFFER
	if (make_shm_block(&shm_id, sizeof(struct shared_mems), (_s8 **) &shm) == -1)
	  goto err;
	if (make_shm_block(&wb1_shmid, DOUBLE_BUFFER_SIZE, &w_buffer_1) == -1)
	  goto err;
	if (make_shm_block(&wb2_shmid, DOUBLE_BUFFER_SIZE, &w_buffer_2) == -1)
	  goto err;
#else    
	shm = malloc(sizeof(struct shared_mems));
	if (shm == NULL) goto err;
	w_buffer_1 = (reall == 1) ? realloc(w_buffer_1, DOUBLE_BUFFER_SIZE) : malloc(DOUBLE_BUFFER_SIZE);
	if (w_buffer_1 == NULL) goto err;
	w_buffer_2 = (reall == 1) ? realloc(w_buffer_2, DOUBLE_BUFFER_SIZE) : malloc(DOUBLE_BUFFER_SIZE);
	if (w_buffer_2 == NULL) goto err;
#endif	
	tr_buffer = malloc(max_tr_size);
	if (tr_buffer == NULL) {
	    goto err;
	}
	read_offset = -1;
	read_buffer_count = 0;
	write_offset = 0;
	write_buffer_count = 0;
	write_pid = 0;
    }
#ifdef TRIPLE_BUFFER
    else {
	shmctl(wb_shm_id, IPC_RMID, 0);		 /* so get rid of original one */
	shmdt(write_buffer);			 
    }
    if (make_shm_block(&wb_shm_id, block_size, (_s8 **) &write_buffer) == -1)
      goto err;
#else    
    write_buffer = (reall == 1) ? realloc(write_buffer, block_size) : malloc(block_size);
    if (write_buffer == NULL) goto err;
#endif    
    return 0;
    
    err:;					 /* error occurred */
    if (read_buffer) {
	free(read_buffer);		 /* free whatever we allocated */
	read_buffer = NULL;
    }
    if (tr_buffer) {
	free(tr_buffer);
	tr_buffer = NULL;
    }
#ifdef TRIPLE_BUFFER
    if (write_buffer) {
	shmctl(wb_shm_id, IPC_RMID, 0);		 /* so get rid of original one */
	shmdt(write_buffer);			 
    }
    if (w_buffer_1) {
	shmctl(wb1_shmid, IPC_RMID, 0);		 /* so get rid of original one */
	shmdt((char *) w_buffer_1);			 
    }
    if (w_buffer_2) {
	shmctl(wb2_shmid, IPC_RMID, 0);		 /* so get rid of original one */
	shmdt((char *) w_buffer_2);			 
    }
    if (shm) {
	shmctl(shm_id, IPC_RMID, 0);		 /* so get rid of original one */
	shmdt((char *) shm);			 
    }
#else
    if (write_buffer) {
	free(write_buffer);
	write_buffer = NULL;
    }
    if (w_buffer_1) {
	free(w_buffer_1);
	w_buffer_1 = NULL;
    }
    if (w_buffer_2) {
	free(w_buffer_2);
	w_buffer_2 = NULL;
    }
    if (shm) {
	free(shm);
	shm = NULL;
    }
#endif
    return do_exit(ERROR_MEMORY);
}


void free_buffers()
{
    if (tr_buffer) {
	free(tr_buffer);
	tr_buffer = NULL;
    }
    if (read_buffer) {
	free(read_buffer);
	read_buffer = NULL;
    }
#ifdef TRIPLE_BUFFER    
    if (log_level > 3) write_log("Detaching shared buffers");
    shmdt(write_buffer);			 /* remove write buffer */
    shmdt((char *) w_buffer_1);			 
    shmdt((char *) w_buffer_2);			 
    shmdt((char *) shm);			 /* remove write buffer */
    shmctl(shm_id, IPC_RMID, 0);		 /* destroy buffers */
    shmctl(wb_shm_id, IPC_RMID, 0);		 /* and shared mems */
    shmctl(wb1_shmid, IPC_RMID, 0);		 
    shmctl(wb2_shmid, IPC_RMID, 0);		 
#else
    if (write_buffer) {
	free(write_buffer);
	write_buffer = NULL;
    }
    if (w_buffer_1) {
	free(w_buffer_1);
	w_buffer_1 = NULL;
    }
    if (w_buffer_2) {
	free(w_buffer_2);
	w_buffer_2 = NULL;
    }
    if (shm) {
	free(shm);
	shm = NULL;
    }
#endif
}


char *print_kb(char *s1, _u32 bytes)
{
/* Prints bytes as x,xxx KB 
 * The string returned is just the string passed
 */
    char s[100];
    
    sprintf(s1, "%sK", convert(s, (float) bytes/(float) 1024));
    return s1;
}

char *print_mb(char *s1, _u32 bytes)
{
/* Prints bytes as x.xxMB 
 * The string returned is just the string passed
 */
    
    char s[100];
    _u32 x;

    strcpy(s1, convert(s, (float) bytes/(float) 1048576));
    x = ((float) ((float) (bytes%1048576) / (float) 1048576) * 10);
    sprintf(s1, "%s.%dMB", s1, x);
    return s1;
}


char *pr_size(char *s1, _u32 bytes)
{
    if (bytes > 1048576) return print_mb(s1, bytes);
    if (bytes > 1024) return print_kb(s1, bytes);
    return convert(s1, bytes);
}
    
void clear_main()
{
    char s[100];
    
    my_werase(win_main, COLOR_MAIN); 
    strcpy(s, "Taper - Linux Backup for ");
    strcat(s, make_tt(tape_type));
    centre(title, 0, s, COLOR_TITLE);
    print_my_name();
    wrefresh(title); wrefresh(win_main);
}


_errstat read_into_temp(struct file_info *fi, char *tmpf, char *fn)
{
/* Read the file next on the tape to a temporary file 
 
 * Accepts  struct file_info *fi   file info for the file
 *          tmpf                   pointer to file to save file as
 * 
 * Returns -1 if error
 *         -2 if checksum error
 */
    _s32 sz, tr, x, chk;
    _s32 c1;
    int of, ret=0;
    char l[MAX_FNAME];
    
    of = creat(tmpf, S_IREAD|S_IWRITE);		 /* create a temporary file */
    if (of==-1) {				 /* to put data in */
	sprintf(l, "while creating temp file to receive data for %s", fn);
	write_error_log(l);
	return -1;
    }
    						 /* copy file to temporary file */
    sz = fi->act_size;				 /* from tape drive */
    sprintf(l, "Read in data for %s from tape to %s", fn, tmpf);
    if (log_level > 2) write_log(l);
    chk=0;
    c1=0;
    while (1) {					 /* copy file accross */
	tr = min(sz, max_tr_size); 
	x = tape_read(tr_buffer, tr);		 /* from device file   */
	if (!x) break;
	if (x == -1) {
	    c1 = -1;
	    break;
	}
	chk += mem_calc_checksum(tr_buffer, x);	 /* calculate checksum */
	sz -= x;
	if (c1 != -1) {				 /* if there have been no previous write errors */
	    c1 = write(of, tr_buffer, x);	 /* if there has been a prev write error */
	    if (c1 == -1) {			 /* still continue reading to pass by file on device  */
		write_error_log(l);
		break;
	    }
	}
	if (!sz) break;				 /* read all we need to */
    }
    if (c1 != -1) {
	if (labs(chk) != fi->checksum) {
	    sprintf(l, "ERROR:  Checksum error for file %s - should be %d but found %ld",
		    fn, fi->checksum, labs(chk));
	    write_log(l);
	    log_errors++;
	    ret = -2;
	}
	else {
	    sprintf(l, "Checksum OK for file %s", fn);
	    if (log_level > 1) write_log(l);
	}
    }
    close(of);
    if (c1==-1)  {
	unlink(tmpf);
	return -1;
    }
    return ret;
}


_errstat read_u32(int fd, _u32 *x)
{
/* Reads an usigned 32 bit integer from the file
 * 
 * Takes into account big/little endian 
 * 
 * Returns -1 if error, 0 otherwise
 */
    char s[sizeof(_u32)];
    
    if (read(fd, s, sizeof(s)) != sizeof(s)) return -1;
    *x = little2machu32((_u32 *) s);
    return 0;
}


_errstat write_u32(int fd, _u32 *x)
{
/* Reads an usigned 32 bit integer from the file
 * 
 * Takes into account big/little endian 
 * 
 * Returns -1 if error, 0 otherwise
 */
    _s32 s;
    
    s = mach2littleu32(x);
    if (write(fd, (char *) &s, sizeof(s)) != sizeof(s)) return -1;
    return 0;
}


_errstat write_info_rec(_s32 rec, struct info_file_data *i_data)
{
/* Writes i_data in the main inf file

   Returns -1 if error, 0 otherwise

   NOTE: Once a filename has been written once, it can never
   change!
 */
    struct file_info_file_data i_data1;
    off_t l;
    _u32 fl;
    
    i_data1.recnum = rec;
    i_data1.f = i_data->f;
    if (!i_data->fname_pos) {			 /* filename needs to be */
	l = lseek(info_index[2], 0L, SEEK_END);	 /*  to filename file */
	i_data->fname_pos = l;			 /*  at end of file */
	fl = strlen(i_data->name);		 /* write filename length */
	if (write_u32(info_index[2], &fl) == -1) return -1;
	if (write(info_index[2], i_data->name, fl) == -1) return -1;
    }
    i_data1.fname_pos = i_data->fname_pos;
    fi_endianize2little(&i_data->f, &i_data1.f);
    lseek(info_index[0], (long) ((rec+1)*sizeof(i_data1)), SEEK_SET);
    if (write(info_index[0], &i_data1, sizeof(i_data1)) == -1) return -1;
    return 0;
}


_errstat read_info_filename(off_t pos, char *name)
{
    /* Reads in the filename that for i_data

       Returns -1 if error, 0 otherwise */

    _u32 fl;
    
    lseek(info_index[2], pos, SEEK_SET);	 /* now read in filename */
    if (read_u32(info_index[2], &fl) == -1) return -1;
    if (read(info_index[2], name, fl) ==-1) return -1;
    name[fl]=0;					 /* terminator */
    return 0;
}


char *get_fn1(off_t pos)
{
    /* reads in the filename at offset 'pos' and
       returns a static string to it */

    static char s[MAX_FNAME];

    switch(pos) {
    case -1:
	strcpy(s, blank_fname); break;
    case 0:
	strcpy(s, ""); break;
    default:
	read_info_filename(pos, s); break;
    }
    return s;
}

char *get_fn2(off_t pos)
{
    /* reads in the filename at offset 'pos' and
       returns a static string to it */

    static char s[MAX_FNAME];
    
    switch(pos) {
    case -1:
	strcpy(s, blank_fname); break;
    case 0:
	strcpy(s, ""); break;
    default:
	read_info_filename(pos, s); break;
    }
    return s;
}

_errstat read_info_rec(_s32 rec, struct info_file_data *i_data)
{
/* Reads i_data in the main inf file

   Returns -1 if error, 0 otherwise
 */

    struct file_info_file_data i_data1;
    
    lseek(info_index[0], (long) ((rec+1)*sizeof(i_data1)), SEEK_SET);
    if (read(info_index[0], &i_data1, sizeof(i_data1)) == -1) return -1;
    i_data->recnum = i_data1.recnum;
    i_data->f = i_data1.f;
    i_data->fname_pos = i_data1.fname_pos;
    fi_endianize2mach(&i_data1.f, &i_data->f);
    return read_info_filename(i_data->fname_pos, i_data->name);
}


void fill_info_key(struct info_file_data i_data, struct info_file_key *i_key)
{
/* Fills in the key given the data structure */

    memset(i_key, 0, sizeof(*i_key));
    i_key->volume = i_data.f.volume;
    i_key->mtime = i_data.f.mtime;
    i_key->pos_in_archive = i_data.f.pos_in_archive;
    i_key->recnum = i_data.recnum;
    i_key->fname_pos = i_data.fname_pos;
}

_errstat add_to_info_index(struct info_file_data *id)
{
    /* Adds id to the indicies */

    
    struct info_file_key i_key;
    int x;
    
    fill_info_key(*id, &i_key);
    for (x=0; x<INFO_INDICIES-1; x++) 		 /* add to recnumes */
	insertb(0, &i_key, x);
    return 0;
}


_errstat add_to_info(struct file_info *fi, char *name, char in_recnum)
{
    /* Adds an entry to the info file.

       If in_recnum == TRUE, adds to indicies. If false, doesn't */

    struct info_file_data i_data;
    
    memset(&i_data, 0, sizeof(i_data));
    fi->name_len = make4len(name);
    i_data.f = *fi; strcpy(i_data.name, name);
    i_data.recnum = ifd.no_in_archive; ifd.no_in_archive++;
    if (write_info_rec(i_data.recnum, &i_data) == -1)
	return do_exit(ERROR_WRITING_INFO);
    if (in_recnum) return add_to_info_index(&i_data);
    return 0;
    
}


_errstat write_info_file()
{
/* Writes out the main info file

 * Assumes file is open
 * 
 * Writes in little endian format
 * 
 * Returns -1 if error, 0 otherwise
*/
    struct info_file_header ifd1;
    struct volume_header vh, vh1;
    struct volume_tape_info vti, vti1;
    struct tape_size_info xtsi, tsi1;
    char *cp;
    _u32 c=0;
    
    if (log_level > 2) write_log("Writing info information");
    ifd_endianize2little(&ifd, &ifd1);
    lseek(info_fd, 0, SEEK_SET);
    if (write(info_fd, &ifd1, sizeof(struct info_file_header)) != sizeof(struct info_file_header)) 
      return do_exit(ERROR_WRITING_INFO);
    cp = (char *) vol_headers;
    for (c=0; c<ifd.number_volumes; c++) {
	memcpy(&vh, cp, sizeof(struct volume_header));   /* for boundary */
	volheader_endianize2little(vh, &vh1);	 /* write out volume header */
	if (write(info_fd, &vh1, sizeof(struct volume_header)) != sizeof(struct volume_header))
	  return do_exit(ERROR_WRITING_INFO);
	cp += sizeof(struct volume_header);	 
	if (write(info_fd, cp, vh.size_header-sizeof(struct volume_header)) != vh.size_header-sizeof(struct volume_header))   /* write out strings */
	  return do_exit(ERROR_WRITING);
	cp += vh.size_header-sizeof(struct volume_header);
    }

    cp = (char *) vt_info;
    for (c=0; c<ifd.number_volumes; c++) {
	memcpy(&vti, cp, sizeof(struct volume_tape_info));/* for boundary */
	vti_endianize2little(&vti, &vti1);
	if (write(info_fd, &vti1, sizeof(struct volume_tape_info)) != sizeof(struct volume_tape_info))
	  return do_exit(ERROR_WRITING_INFO);
	cp += sizeof(struct volume_tape_info);
    }
    
    if (ifd.number_tsi) {
	cp = (char *) tsi;
	for (c=0; c<ifd.number_tsi; c++) {
	    memcpy(&xtsi, cp, sizeof(struct tape_size_info));   /* boundary issue */
	    tsi_endianize2little(&xtsi,&tsi1);
	    if (write(info_fd, &tsi1, sizeof(struct tape_size_info)) != sizeof(struct tape_size_info))
	      return do_exit(ERROR_WRITING_INFO);
	    cp += sizeof(struct tape_size_info);
	}
    }
    return 0;
}


_errstat read_volume_info()
{
/* Reads the volume information and vt_info into memory

 * assumes that info file header has already been read and
 * file (already opened) 
 * 
 * Returns -1 if error, 0 otherwise
*/
    struct volume_header vh, vh1;
    struct volume_tape_info vti, vti1;
    struct tape_size_info xtsi, tsi1;
    char *cp;
    _u32 c;
    
    if (log_level > 2) write_log("Reading volume info");
    
    cp = (char *) vol_headers;
    for (c=0; c<ifd.number_volumes; c++) {
	if (read(info_fd, &vh, sizeof(struct volume_header)) != sizeof(struct volume_header))
	  return do_exit(ERROR_READING_INFO);
	volheader_endianize2mach(vh, &vh1);	 /* write out volume header */
	memcpy(cp, &vh1, sizeof(struct volume_header));   /* for boundary */
	cp += sizeof(struct volume_header);
	if (read(info_fd, cp, vh1.size_header-sizeof(struct volume_header)) != vh1.size_header - sizeof(struct volume_header))
	  return do_exit(ERROR_READING_INFO);
	cp += vh1.size_header-sizeof(struct volume_header);
    }

    cp = (char *) vt_info;
    for (c=0; c<ifd.number_volumes; c++) {
	if (read(info_fd, &vti, sizeof(struct volume_tape_info)) != sizeof(struct volume_tape_info))
	  return do_exit(ERROR_READING_INFO);
	vti_endianize2mach(&vti, &vti1);
	memcpy(cp, &vti1, sizeof(struct volume_tape_info));/* for boundary */
	cp += sizeof(struct volume_tape_info);
    }
    
    if (ifd.number_tsi) {
	cp = (char *) tsi;
	for (c=0; c<ifd.number_tsi; c++) {
	    if (read(info_fd, &xtsi, sizeof(struct tape_size_info)) != sizeof(struct tape_size_info))
	      return do_exit(ERROR_READING_INFO);
	    tsi_endianize2mach(&xtsi,&tsi1);
	    memcpy(cp, &tsi1, sizeof(struct tape_size_info));   /* boundary issue */
	    cp += sizeof(struct tape_size_info);
	}
    }
    return 0;
}


int open_uncompress_file(char *file, int allowerr)
	/* What do you think?

	   Overwrites the compressed file with the uncompressed one

	   If the file is not compressed, returns

	   Returns file handle of open file

	 */
{
    char tmpf[MAX_FNAME], s[MAX_FNAME];
    int ifd, ofd;
    _u32 id, id1;
    
    sprintf(s, "Uncompressing file %s", file);
    if (log_level > 2) write_log(s);
    taper_tmpnam(tmpf);
    if (log_level > 2) write_log("Opening compressed file");
    ifd = open(file, O_RDWR);
    if (ifd == -1) {
	if (allowerr)
	    return -1;
	else
	    return do_exit(ERROR_UNCOMPRESSING_INFO);
    }
    if (read(ifd, &id, sizeof(id)) != sizeof(id))
	return do_exit(ERROR_UNCOMPRESSING_INFO);
    id1 = little2machs32(&id);
    if (id1 != COMPRESSED_MAGIC)
	return ifd;				 /* file is not compressed */
    if (log_level > 2) write_log("Creating temp file to uncompress to");
    ofd = creat(tmpf, S_IREAD|S_IWRITE);
    if (ofd == -1) {
	close(ifd);
	return do_exit(ERROR_UNCOMPRESSING_INFO);
    }
    id = 0;
    if (write(ofd, &id, sizeof(_u32)) != sizeof(_u32))
	return do_exit(ERROR_UNCOMPRESSING_INFO); /* indicates it isn't compressed */
    if (unzip(ifd, ofd) != 0) {
	close(ofd); close(ifd);
	unlink(tmpf);
	return do_exit(ERROR_UNCOMPRESSING_INFO);
    }
    close(ifd); close(ofd);

    unlink(file);				 /* remove compressed file */
    my_rename(tmpf, file);			 /* rename file */
    return open(file, O_RDWR);			 /* open the uncompressed file */
}


_errstat compress_file(char *file)
{
    /* As the name suggests

       At the beginning of each file, there should be 32 bits which indicates
       if the file is compressed or not

     */

    int ifd, ofd=0;
    char tmpf[MAX_FNAME];
    char s[MAX_FNAME];
    _u32 id, id1;

    sprintf(s, "Compressing file %s", file);
    if (log_level > 2) write_log(s);
    ifd = open(file, O_RDONLY);		 /* open orig info file */
    if (ifd==-1) {
	write_error_log(s);
	goto err;
    }
    if (read(ifd, &id, sizeof(id)) != sizeof(id)) {
	write_error_log("reading original compression marker");
	goto err;
    }

    id1 = little2machs32(&id);
    if (id1 == COMPRESSED_MAGIC) {		 /* already compressed  */
	close(ifd);
	return 0;
    }
    
    if (log_level > 2) write_log("Creating temp file");
    taper_tmpnam(tmpf);
    ofd = creat(tmpf, S_IREAD|S_IWRITE);
    if (ofd==-1) {
	write_error_log("creating temp file");
	goto err;
    }
    id = COMPRESSED_MAGIC;  id1 = mach2littles32(&id);
    if (write(ofd, &id1, sizeof(id)) != sizeof(id)) {
	write_error_log("writing compression marker");
	goto err;
    }
    zip(ifd, ofd);
    close(ifd); close(ofd);
    ifd = 0; ofd = 0;
    unlink(file);				 /* remove original */
    my_rename(tmpf, file);			 /* rename compressed to original */
    return 0;
    
    err:;
      if (ifd) close(ifd);
      if (ofd) close(ofd);
      if (*tmpf) unlink(tmpf);
      return -1;
}


_errstat compress_info_file(_u32 archive_id)
{
/* Compresses info file. If can't, uncompressed file is left
 * alone. The info file header is left uncompressed.

 Assumes that the info file is closed

 */
    
    int x;
    char ifile[MAX_FNAME], s[MAX_FNAME];
    
    if (log_level > 1) write_log("Compressing info file");
    make_info_filename(ifile, archive_id);	 /* make info filename */
    for (x=0; x<=INFO_INDICIES; x++) {
	sprintf(s, "%s.%d", ifile, x);
	if (compress_file(s) == -1) return -1;
    }
    return 0;
}


void close_info_file()
{
    int x;
    
    /* Closes the info file and sets file handles to zero */
    if (info_fd) close(info_fd);
    info_fd = 0;
    for (x=0; x<=INFO_INDICIES; x++) {
	if (info_index[x]) close(info_index[x]);
	info_index[x] = 0;
    }
    if (compress_info) compress_info_file(ifd.archive_id);
}


void make_info_filename(char *info_file, _u32 archive_id)
{
    strcpy(info_file, taper_info_files);	 /* look for information file */
    if (info_file[strlen(info_file)-1] != '/')	 /* associated with this archive */
      strcat(info_file, "/");
    sprintf(info_file, "%staper_info.%u", info_file, archive_id);
}


_errstat open_one_index(char *info_file,_s8 must_exist, _s8 recnum)
{
    char s[MAX_FNAME];
	
    sprintf(s, "%s.%d", info_file, recnum);
    if (log_level > 2) write_log("Opening index file");
    while (1) {
	info_index[recnum] = open_uncompress_file(s, 1); /* open information file */
	if ((info_index[recnum] == -1) && (must_exist)) /* error if doesn't exist */
		return do_exit(ERROR_NO_INFO);	 /* and it must */
	if (info_index[recnum] != -1)
	    break;
	if (log_level > 2) write_log("Creating index");
	info_index[recnum] = open(s, O_RDWR|O_CREAT, S_IWRITE|S_IREAD);
	if (info_index[recnum] != -1) {
	    write(info_index[recnum], 0, sizeof(_u32)); /* magic # for compression */
	    lseek(info_index[recnum], 0, sizeof(_u32));
	    break;
	}
    }
    return 0;
}


_errstat open_info_file(char must_exist, _u32 archive_id, _s8 open_recnum)
{
/* Opens an info file with indices -
     if must_exist, then exists with an error if file(s) don't exist
       otherwise creates

   An info file consists of the following files:

       taper_xxxxx     = file that contains header info + vol header
       taper_xxxxx.0   = file with file_info (main file)
       taper_xxxxx.1   = index file
       taper_xxxxx.2   = filename file - text file containing filenames

   If open_recnum, then recnum file is opened, otherwise not
   
   Returns -1 if error, 0 otherwise
 */

    char    info_file[MAX_FNAME];
    int x, c;

    if (make_info_dirs() == -1) return -1;	 /* make directories */
    make_info_filename(info_file, archive_id);	 /* make info filename */
    
    if (log_level > 1) write_log("Opening info file");
    while (1) {
	info_fd = open(info_file, O_RDWR);	 /* don't compress this */
	if ((info_fd == -1) && (must_exist))	 /* error if doesn't exist */
	    return do_exit(ERROR_NO_INFO);	 /* and it must */
	if (info_fd != -1)  break;
	if (log_level > 2) write_log("Creating info file");
	info_fd = open(info_file, O_RDWR|O_CREAT, S_IWRITE|S_IREAD);
	if (info_fd != -1) break;
	if (!no_windows) return do_exit(ERROR_CREATING_INFO);
	if (retryabort("creating the info file") == -1)
	    return do_exit(ERROR_CREATING_INFO);
    }
    for (x=0; x<=INFO_INDICIES; x++) {
	if ((!open_recnum) && x) break;
	if (open_one_index(info_file, must_exist, x) == -1) {
	    if (!no_windows) {
		for (c=0; c<x; c++) close(info_index[c]);
		return do_exit(ERROR_CREATING_INFO);
	    }
	    if (retryabort("creating the info file") == -1) {
		for (c=0; c<x; c++) close(info_index[c]);
		return do_exit(ERROR_CREATING_INFO);
	    }
	    return -1;
	}
    }
    return 0;
}


void del_info_file(_u32 archive_id)
{
/* Deletes an info file - closes first
     if must_exist, then exists with an error if file(s) don't exist

     An info file consists of the following files:

       taper_xxxxx     = file that contains header info + vol header
       taper_xxxxx.0   = file with file_info (main file)
       taper_xxxxx.1  )

       Returns -1 if error, 0 otherwise
 */

    char    info_file[MAX_FNAME], s[MAX_FNAME];
    int x;

    if (make_info_dirs() == -1) return;		 /* make directories */
    make_info_filename(info_file, archive_id);	 /* make info filename */
    
    if (log_level > 2) write_log("Deleting info file");
    if (info_fd > 0) close(info_fd);
    for (x=0; x<=INFO_INDICIES; x++)
	if (info_index[x] > 0) close(info_index[x]);
    unlink(info_file);
    for (x=0; x<=INFO_INDICIES; x++) {
	sprintf(s, "%s.%d", info_file, x);
	unlink(s);
       info_index[x] = 0;
    }
   info_fd = 0;
}



void set_1s_timer()
{
#ifdef BSD_SIGNALS
    /* Sets a 1 second timer */    
    struct itimerval itv1;
    struct timeval itv, val;

    val.tv_sec = 1;
    val.tv_usec = 0;
    itv.tv_sec = 1;
    itv.tv_usec = 0;
    itv1.it_value = val;
    itv1.it_interval = itv;
    setitimer(ITIMER_REAL, &itv1, NULL);
#else
    alarm(1);
#endif
}


void reset_timer()
{
#ifdef BSD_SIGNALS
    /* Clears timer * - all resets signal handler */
    struct itimerval itv1;
    struct timeval itv, val;

    val.tv_sec = 0;
    val.tv_usec = 0;
    itv.tv_sec = 0;
    itv.tv_usec = 0;
    itv1.it_value = val;
    itv1.it_interval = itv;
    setitimer(ITIMER_REAL, &itv1, NULL);
#else
    alarm(0);
#endif
    signal(SIGALRM, SIG_DFL);
}


void retrigger_alarm()
{
#ifndef BSD_SIGNALS
    alarm(1);
#endif
}


_s8 chk_sel_excl(char *s)
{
    /* See if 's' is in the exclusion or inclusion list

       Returns TRUE if it is, FALSE otherwise
    */

    _s32 c;
    struct selected_entry *se;

    
    se = sel_files;
    for (c=0; c<no_sel; c++) {
	if (!strcmp(se->i.name, s)) return TRUE;
	se++;
    }
    se = excluded_files;
    for (c=0; c<no_exclude; c++) {
	if (!strcmp(se->i.name, s)) return TRUE;
	se++;
    }
    return FALSE;
}


char *get_line(char *s, FILE *f)
{
    /* Gets a line, strips of terminal \n
       ignores blank lines */

    while (1) {
	if (fgets(s, MAX_FNAME, f) == NULL) return NULL; /* EOF */
	if (s[strlen(s)-1] == '\n')
	  s[strlen(s)-1] = 0;
	if (*s) break;
    }
    return s;
}


void strip_trailing_spaces(char *s)
{
    char *s1=&s[strlen(s)]-1;

    while ((*s1 == ' ') && (s1 >= s)) {
	*s1 = 0;
	s1--;
    }
}