File: ad_save_load.cxx

package info (click to toggle)
arb 6.0.2-1%2Bdeb8u1
  • links: PTS, VCS
  • area: non-free
  • in suites: jessie
  • size: 65,916 kB
  • ctags: 53,258
  • sloc: ansic: 394,903; cpp: 250,252; makefile: 19,620; sh: 15,878; perl: 10,461; fortran: 6,019; ruby: 683; xml: 503; python: 53; awk: 32
file content (1693 lines) | stat: -rw-r--r-- 58,038 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
// =============================================================== //
//                                                                 //
//   File      : ad_save_load.cxx                                  //
//   Purpose   :                                                   //
//                                                                 //
//   Institute of Microbiology (Technical University Munich)       //
//   http://www.arb-home.de/                                       //
//                                                                 //
// =============================================================== //

#include <unistd.h>
#include <sys/stat.h>
#include <netinet/in.h>

#include <arb_file.h>
#include <arb_diff.h>

#include "gb_key.h"
#include "gb_map.h"
#include "gb_load.h"
#include "ad_io_inline.h"

GB_MAIN_TYPE *gb_main_array[GB_MAIN_ARRAY_SIZE];

char *gb_findExtension(char *path) {
    char *punkt = strrchr(path, '.');
    if (punkt) {
        char *slash = strchr(punkt, '/');
        if (slash) punkt = 0;   //  slash after '.' -> no extension
    }
    return punkt;
}


/* CAUTION!!!
 *
 * The following functions (gb_quicksaveName, gb_oldQuicksaveName, gb_mapfile_name, gb_overwriteName)
 * use static buffers for the created filenames.
 *
 * So you have to make sure, to use only one instance of every of these
 * functions or to dup the string before using the second instance
 */

inline char *STATIC_BUFFER(SmartCharPtr& strvar, int minlen) {
    gb_assert(minlen > 0);
    if (strvar.isNull() || (strlen(&*strvar) < (size_t)(minlen-1))) {
        strvar = (char*)GB_calloc(minlen, 1);
    }
    return &*strvar;
}

GB_CSTR gb_oldQuicksaveName(GB_CSTR path, int nr) {
    static SmartCharPtr Qname;

    size_t  len   = strlen(path);
    char   *qname = STATIC_BUFFER(Qname, len+15);
    strcpy(qname, path);

    char *ext     = gb_findExtension(qname);
    if (!ext) ext = qname + len;

    if (nr==-1) sprintf(ext, ".arb.quick?");
    else    sprintf(ext, ".arb.quick%i", nr);

    return qname;
}

GB_CSTR gb_quicksaveName(GB_CSTR path, int nr) {
    static SmartCharPtr Qname;

    char *qname = STATIC_BUFFER(Qname, strlen(path)+4);
    strcpy(qname, path);

    char *ext     = gb_findExtension(qname);
    if (!ext) ext = qname + strlen(qname);

    if (nr==-1) sprintf(ext, ".a??");
    else    sprintf(ext, ".a%02i", nr);

    return qname;
}

GB_CSTR gb_mapfile_name(GB_CSTR path) {
    static SmartCharPtr Mapname;

    char *mapname = STATIC_BUFFER(Mapname, strlen(path)+4+1);
    strcpy(mapname, path);

    char *ext     = gb_findExtension(mapname);
    if (!ext) ext = mapname + strlen(mapname);

    strcpy(ext, ".ARM");

    return mapname;
}

GB_CSTR GB_mapfile(GBDATA *gb_main) {
    GB_MAIN_TYPE *Main = GB_MAIN(gb_main);
    return gb_mapfile_name(Main->path);
}

static GB_CSTR gb_overwriteName(GB_CSTR path) {
    static SmartCharPtr Oname;

    int   len   = strlen(path);
    char *oname = STATIC_BUFFER(Oname, len+2);

    strcpy(oname, path);
    strcpy(oname+len, "~");                         // append ~

    return oname;
}

static GB_CSTR gb_reffile_name(GB_CSTR path) {
    static SmartCharPtr Refname;

    size_t  len     = strlen(path);
    char   *refname = STATIC_BUFFER(Refname, len+4+1);
    memcpy(refname, path, len+1);

    const char *ext        = gb_findExtension(refname);
    size_t      ext_offset = ext ? (size_t)(ext-refname) : len;

    strcpy(refname+ext_offset, ".ARF");

    return refname;
}

static char *gb_full_path(const char *path) {
    char *res = 0;

    if (path[0] == '/') res = strdup(path);
    else {
        const char *cwd = GB_getcwd();

        if (path[0] == 0) res = strdup(cwd);
        else res              = GBS_global_string_copy("%s/%s", cwd, path);
    }
    return res;
}

static GB_ERROR gb_delete_reference(const char *master) {
    GB_ERROR    error      = 0;
    char       *fullmaster = gb_full_path(master);
    const char *fullref    = gb_reffile_name(fullmaster);

    GB_unlink_or_warn(fullref, &error);

    free(fullmaster);
    return error;
}

static GB_ERROR gb_create_reference(const char *master) {
    char       *fullmaster = gb_full_path(master);
    const char *fullref    = gb_reffile_name(fullmaster);
    GB_ERROR    error      = 0;
    FILE       *out        = fopen(fullref, "w");

    if (out) {
        fprintf(out, "***** The following files may be a link to %s ********\n", fullmaster);
        fclose(out);
        error = GB_set_mode_of_file(fullref, 00666);
    }
    else {
        error = GBS_global_string("Cannot create reference file '%s'\n"
                                  "Your database was saved, but you should check "
                                  "write permissions in the destination directory!", fullref);
    }

    free(fullmaster);
    return error;
}

static GB_ERROR gb_add_reference(const char *master, const char *changes) {
    char       *fullmaster  = gb_full_path(master);
    char       *fullchanges = gb_full_path(changes);
    const char *fullref     = gb_reffile_name(fullmaster);
    GB_ERROR    error       = 0;
    FILE       *out         = fopen(fullref, "a");

    if (out) {
        fprintf(out, "%s\n", fullchanges);
        fclose(out);
        error = GB_set_mode_of_file(fullref, 00666);
    }
    else {
        error = GBS_global_string("Cannot add your file '%s'\n"
                                  "to the list of references of '%s'.\n"
                                  "Please ask the owner of that file not to delete it\n"
                                  "or save the entire database (that's recommended!)",
                                  fullchanges, fullref);
    }

    free(fullchanges);
    free(fullmaster);

    return error;
}

static GB_ERROR gb_remove_quick_saved(GB_MAIN_TYPE *Main, const char *path) {
    int i;
    GB_ERROR error = 0;

    for (i=0; i<GB_MAX_QUICK_SAVE_INDEX && !error; i++) GB_unlink_or_warn(gb_quicksaveName(path, i), &error);
    for (i=0; i<10 && !error; i++) GB_unlink_or_warn(gb_oldQuicksaveName(path, i), &error);
    if (Main) Main->qs.last_index = -1;

    RETURN_ERROR(error);
}

static GB_ERROR gb_remove_all_but_main(GB_MAIN_TYPE *Main, const char *path) {
    GB_ERROR error = gb_remove_quick_saved(Main, path);
    if (!error) GB_unlink_or_warn(gb_mapfile_name(path), &error); // delete old mapfile

    RETURN_ERROR(error);
}

static GB_ERROR deleteSuperfluousQuicksaves(GB_MAIN_TYPE *Main) {
    int       cnt   = 0;
    int       i;
    char     *path  = Main->path;
    GB_ERROR  error = 0;

    for (i=0; i <= GB_MAX_QUICK_SAVE_INDEX; i++) {
        GB_CSTR qsave = gb_quicksaveName(path, i);
        if (GB_is_regularfile(qsave)) cnt++;
    }

    for (i=0; cnt>GB_MAX_QUICK_SAVES && i <= GB_MAX_QUICK_SAVE_INDEX && !error; i++) {
        GB_CSTR qsave = gb_quicksaveName(path, i);
        if (GB_is_regularfile(qsave)) {
            if (GB_unlink(qsave)<0) error = GB_await_error();
            else cnt--;
        }
    }

    return error;
}

static GB_ERROR renameQuicksaves(GB_MAIN_TYPE *Main) {
    /* After hundred quicksaves rename the quicksave-files to a00...a09
     * to keep MS-DOS-compatibility (8.3)
     * Note: This has to be called just before saving.
     */

    GB_ERROR error = deleteSuperfluousQuicksaves(Main);
    if (!error) {
        const char *path = Main->path;
        int         i;
        int         j;

        for (i=0, j=0; i <= GB_MAX_QUICK_SAVE_INDEX; i++) {
            GB_CSTR qsave = gb_quicksaveName(path, i);

            if (GB_is_regularfile(qsave)) {
                if (i!=j) {                         // otherwise the filename is correct
                    char    *qdup = strdup(qsave);
                    GB_CSTR  qnew = gb_quicksaveName(path, j);

                    if (error) GB_warning(error);
                    error = GB_rename_file(qdup, qnew);
                    free(qdup);
                }

                j++;
            }
        }

        gb_assert(j <= GB_MAX_QUICK_SAVES);
        Main->qs.last_index = j-1;
    }

    return error;
}

// ------------------------
//      Ascii to Binary

long gb_ascii_2_bin(const char *source, GBENTRY *gbe) {
    const char *s = source;
    char        c = *(s++);

    A_TO_I(c);
    gbe->flags.compressed_data = c;

    long size;
    if (*s == ':') {
        size = 0;
        s++;
    }
    else {
        long i, k;
        for (i = 0, k = 8; k && (c = *(s++)); k--) {
            A_TO_I(c);
            i = (i<<4)+c;
        }
        size = i;
    }
    source = s;

    long len = 0;
    while ((c = *(s++))) {
        if ((c == '.') || (c=='-')) {
            len++;
            continue;
        }
        if ((c == ':') || (c=='=')) {
            len += 2;
            continue;
        }
        if (!(c = *(s++))) {
            return 1;
        };
        len++;
    }

    GBENTRY_memory storage(gbe, size, len);

    char *d = storage;
    s       = source;

    while ((c = *(s++))) {
        if (c == '.') {
            *(d++)=0;
            continue;
        }
        if (c == ':') {
            *(d++)=0;
            *(d++)=0;
            continue;
        }
        if (c == '-') {
            *(d++) = 0xff;
            continue;
        }
        if (c == '=') {
            *(d++) = 0xff;
            *(d++) = 0xff;
            continue;
        }
        A_TO_I(c);
        long i = c << 4;
        c = *(s++);
        A_TO_I(c);
        *(d++) = (char)(i + c);
    }

    return 0;
}
// ------------------------
//      Binary to Ascii

#define GB_PUT(c, out) do { if (c>=10) c+='A'-10; else c += '0'; *(out++) = (char)c; } while (0)

static GB_BUFFER gb_bin_2_ascii(GBENTRY *gbe) {
    signed char   *s, *out, c, mo;
    unsigned long  i;
    int            j;
    char          *buffer;
    int            k;

    const char *source     = gbe->data();
    long        len        = gbe->memsize();
    long        xtended    = gbe->size();
    int         compressed = gbe->flags.compressed_data;

    buffer = GB_give_buffer(len * 2 + 10);
    out = (signed char *)buffer;
    s = (signed char *)source, mo = -1;

    GB_PUT(compressed, out);
    if (!xtended) {
        *(out++) = ':';
    }
    else {
        for (i = 0xf0000000, j=28; j>=0; j-=4, i=i>>4) {
            k = (int)((xtended & i)>>j);
            GB_PUT(k, out);
        }
    }
    for (i = len; i; i--) {
        if (!(c = *(s++))) {
            if ((i > 1) && !*s) {
                *(out++) = ':';
                s ++;
                i--;
                continue;
            }
            *(out++) = '.';
            continue;
        }
        if (c == mo) {
            if ((i > 1) && (*s == -1)) {
                *(out++) = '=';
                s ++;
                i--;
                continue;
            }
            *(out++) = '-';
            continue;
        }
        j = ((unsigned char) c) >> 4;
        GB_PUT(j, out);
        j = c & 15;
        GB_PUT(j, out);
    }
    *(out++) = 0;
    return buffer;
}

// -------------------------
//      Write Ascii File

#define GB_PUT_OUT(c, out) do { if (c>=10) c+='A'-10; else c += '0'; putc(c, out); } while (0)

static void gb_write_rek(FILE *out, GBCONTAINER *gbc, long deep, long big_hunk) {
    // used by ASCII database save
    long     i;
    char    *s;
    char     c;
    GBDATA  *gb;
    GB_CSTR  strng;
    char    *key;

    for (gb = GB_child(gbc); gb; gb = GB_nextChild(gb)) {
        if (gb->flags.temporary) continue;
        key = GB_KEY(gb);
        if (!strcmp(key, GB_SYSTEM_FOLDER)) continue;   // do not save system folder
        for (i=deep; i--;) putc('\t', out);
        fprintf(out, "%s\t", key);
        if ((int)strlen(key) < 8) {
            putc('\t', out);
        }
        if (gb->flags.security_delete ||
                gb->flags.security_write ||
                gb->flags.security_read ||
                gb->flags2.last_updated) {
            putc(':', out);
            c = gb->flags.security_delete;
            GB_PUT_OUT(c, out);
            c = gb->flags.security_write;
            GB_PUT_OUT(c, out);
            c = gb->flags.security_read;
            GB_PUT_OUT(c, out);
            fprintf(out, "%u\t", gb->flags2.last_updated);
        }
        else {
            putc('\t', out);
        }

        if (gb->is_container()) {
            fprintf(out, "%%%c (%%\n", GB_read_flag(gb) ? '$' : '%');
            gb_write_rek(out, gb->as_container(), deep+1, big_hunk);
            for (i=deep+1; i--;) putc('\t', out);
            fprintf(out, "%%) /*%s*/\n\n", GB_KEY(gb));
        }
        else {
            GBENTRY *gbe = gb->as_entry();
            switch (gbe->type()) {
                case GB_STRING:
                    strng = GB_read_char_pntr(gbe);
                    if (!strng) {
                        strng = "<entry was broken - replaced during ASCIIsave/arb_repair>";
                        GB_warningf("- replaced broken DB entry %s (data lost)\n", GB_get_db_path(gbe));
                    }
                    if (*strng == '%') {
                        putc('%', out);
                        putc('s', out);
                        putc('\t', out);
                    }
                    GBS_fwrite_string(strng, out);
                    putc('\n', out);
                    break;
                case GB_LINK:
                    strng = GB_read_link_pntr(gbe);
                    if (*strng == '%') {
                        putc('%', out);
                        putc('l', out);
                        putc('\t', out);
                    }
                    GBS_fwrite_string(strng, out);
                    putc('\n', out);
                    break;
                case GB_INT:
                    fprintf(out, "%%i %li\n", GB_read_int(gbe));
                    break;
                case GB_FLOAT:
                    fprintf(out, "%%f %g\n", GB_read_float(gbe));
                    break;
                case GB_BITS:
                    fprintf(out, "%%I\t\"%s\"\n",
                            GB_read_bits_pntr(gbe, '-', '+'));
                    break;
                case GB_BYTES:
                    s = gb_bin_2_ascii(gbe);
                    fprintf(out, "%%Y\t%s\n", s);
                    break;
                case GB_INTS:
                    s = gb_bin_2_ascii(gbe);
                    fprintf(out, "%%N\t%s\n", s);
                    break;
                case GB_FLOATS:
                    s = gb_bin_2_ascii(gbe);
                    fprintf(out, "%%F\t%s\n", s);
                    break;
                case GB_DB:
                    gb_assert(0);
                    break;
                case GB_BYTE:
                    fprintf(out, "%%y %i\n", GB_read_byte(gbe));
                    break;
                default:
                    fprintf(stderr,
                            "ARBDB ERROR Key \'%s\' is of unknown type\n",
                            GB_KEY(gbe));
                    fprintf(out, "%%%% (%% %%) /* unknown type */\n");
                    break;
            }
        }
    }
}

// -------------------------
//      Read Binary File

long gb_read_bin_error(FILE *in, GBDATA *gbd, const char *text) {
    long p = (long)ftell(in);
    GB_export_errorf("%s in reading GB_file (loc %li=%lX) reading %s\n",
                     text, p, p, GB_KEY(gbd));
    GB_print_error();
    return 0;
}

// --------------------------
//      Write Binary File

static int gb_is_writeable(gb_header_list *header, GBDATA *gbd, long version, long diff_save) {
    /* Test whether to write any data to disc.
     *
     * version 1       write only latest data
     * version 2       write deleted entries two (which are not already stored to master file !!!
     *
     * try to avoid to access gbd (to keep it swapped out)
     */
    if (version == 2 && header->flags.changed==GB_DELETED) return 1;    // save delete flag
    if (!gbd) return 0;
    if (diff_save) {
        if (!header->flags.ever_changed) return 0;
        if (!gbd->ext || (gbd->ext->update_date<diff_save && gbd->ext->creation_date < diff_save))
            return 0;
    }
    if (gbd->flags.temporary) return 0;
    return 1;
}

static int gb_write_bin_sub_containers(FILE *out, GBCONTAINER *gbc, long version, long diff_save, int is_root);

static bool seen_corrupt_data = false;

static long gb_write_bin_rek(FILE *out, GBDATA *gbd, long version, long diff_save, long index_of_master_file) {
    int          i;
    GBCONTAINER *gbc  = 0;
    GBENTRY     *gbe  = 0;
    long         size = 0;
    GB_TYPES     type = gbd->type();

    if (type == GB_DB) {
        gbc = gbd->as_container();
    }
    else {
        gbe = gbd->as_entry();
        if (type == GB_STRING || type == GB_STRING_SHRT) {
            size = gbe->size();
            if (!gbe->flags.compressed_data && size < GBTUM_SHORT_STRING_SIZE) {
                const char *data = gbe->data();
                size_t      len  = strlen(data); // w/o zero-byte!

                if ((long)len == size) {
                    type = GB_STRING_SHRT;
                }
                else {
                    // string contains zero-byte inside data or misses trailing zero-byte
                    type              = GB_STRING; // fallback to safer type
                    seen_corrupt_data = true;
                    GB_warningf("Corrupted entry detected:\n"
                                "entry: '%s'\n"
                                "data:  '%s'",
                                GB_get_db_path(gbe),
                                data);
                }
            }
            else {
                type = GB_STRING;
            }
        }
    }

    i =     (type<<4)
        +   (gbd->flags.security_delete<<1)
        +   (gbd->flags.security_write>>2);
    putc(i, out);

    i =     ((gbd->flags.security_write &3) << 6)
        +   (gbd->flags.security_read<<3)
        +   (gbd->flags.compressed_data<<2)
        +   ((GB_ARRAY_FLAGS(gbd).flags&1)<<1)
        +   (gbd->flags.unused);
    putc(i, out);

    gb_put_number(GB_ARRAY_FLAGS(gbd).key_quark, out);

    if (diff_save) {
        gb_put_number(index_of_master_file, out);
    }

    i = gbd->flags2.last_updated;
    putc(i, out);

    if (type == GB_STRING_SHRT) {
        const char *data = gbe->data();
        gb_assert((long)strlen(data) == size);

        i = fwrite(data, size+1, 1, out);
        return i <= 0 ? -1 : 0;
    }

    switch (type) {
        case GB_DB:
            i = gb_write_bin_sub_containers(out, gbc, version, diff_save, 0);
            return i;

        case GB_INT: {
            GB_UINT4 buffer = (GB_UINT4)htonl(gbe->info.i);
            if (!fwrite((char *)&buffer, sizeof(float), 1, out)) return -1;
            return 0;
        }
        case GB_FLOAT:
            if (!fwrite((char *)&gbe->info.i, sizeof(float), 1, out)) return -1;
            return 0;
        case GB_LINK:
        case GB_BITS:
        case GB_BYTES:
        case GB_INTS:
        case GB_FLOATS:
            size = gbe->size();
            // fall-through
        case GB_STRING: {
            long memsize = gbe->memsize();
            gb_put_number(size, out);
            gb_put_number(memsize, out);
            i = fwrite(gbe->data(), (size_t)memsize, 1, out);
            if (memsize && !i) return -1;
            return 0;
        }
        case GB_BYTE:
            putc((int)(gbe->info.i), out);
            return 0;
        default:
            gb_assert(0); // unknown type
            return -1;
    }
}

static int gb_write_bin_sub_containers(FILE *out, GBCONTAINER *gbc, long version, long diff_save, int is_root) {
    gb_header_list *header;
    uint32_t        i, index;

    header = GB_DATA_LIST_HEADER(gbc->d);
    gb_assert(gbc->d.nheader >= 0);
    for (i=0, index = 0; index < (uint32_t)gbc->d.nheader; index++) {
        if (gb_is_writeable(&(header[index]), GB_HEADER_LIST_GBD(header[index]), version, diff_save)) i++;
    }

    if (!is_root) {
        gb_put_number(i, out);
    }
    else {
        gb_write_out_uint32(i, out);
    }

    uint32_t counter = 0;
    for (index = 0; index < (uint32_t)gbc->d.nheader; index++) {
        GBDATA *h_gbd;

        if (header[index].flags.changed == GB_DELETED_IN_MASTER) {  // count deleted items in master, because of index renaming
            counter ++;
            continue;
        }

        h_gbd = GB_HEADER_LIST_GBD(header[index]);

        if (!gb_is_writeable(&(header[index]), h_gbd, version, diff_save)) {
            if (version <= 1 && header[index].flags.changed == GB_DELETED) {
                header[index].flags.changed = GB_DELETED_IN_MASTER; // mark deleted in master
            }
            continue;
        }

        if (h_gbd) {
            i = (int)gb_write_bin_rek(out, h_gbd, version, diff_save, index-counter);
            if (i) return i;
        }
        else {
            if (header[index].flags.changed == GB_DELETED) {
                putc(0, out);
                putc(1, out);
                gb_put_number(index - counter, out);
            }
        }
    }
    return 0;
}

static int gb_write_bin(FILE *out, GBCONTAINER *gbc, uint32_t version) {
    /* version 1 write master arb file
     * version 2 write slave arb file (aka quick save file)
     */

    gb_assert(!seen_corrupt_data);

    int           diff_save = 0;
    GB_MAIN_TYPE *Main      = GBCONTAINER_MAIN(gbc);

    gb_write_out_uint32(GBTUM_MAGIC_NUMBER, out);
    fprintf(out, "\n this is the binary version of the gbtum data file version %li\n", (long)version);
    putc(0, out);
    fwrite("vers", 4, 1, out);
    gb_write_out_uint32(0x01020304, out);
    gb_write_out_uint32(version, out);
    fwrite("keys", 4, 1, out);

    for (long i=1; i<Main->keycnt; i++) {
        if (Main->keys[i].nref>0) {
            gb_put_number(Main->keys[i].nref, out);
            fprintf(out, "%s", Main->keys[i].key);
        }
        else {
            putc(0, out);       // 0 nref
            putc(1, out);       // empty key
        }
        putc(0, out);

    }
    putc(0, out);
    putc(0, out);
    fwrite("time", 4, 1, out); {
        unsigned int k;
        for (k=0; k<Main->last_updated; k++) {
            fprintf(out, "%s", Main->dates[k]);
            putc(0, out);
        }
    }
    putc(0, out);
    fwrite("data", 4, 1, out);
    if (version == 2) diff_save = (int)Main->last_main_saved_transaction+1;

    return gb_write_bin_sub_containers(out, gbc, version, diff_save, 1);
}

// ----------------------
//      save database

GB_ERROR GB_save(GBDATA *gb, const char *path, const char *savetype)
     /* savetype 'a'    ascii
      *          'aS'   dump to stdout
      *          'b'    binary
      *          'bm'   binary + mapfile
      *          0      ascii
      */
{
    if (path && strchr(savetype, 'S') == 0) // 'S' dumps to stdout -> do not change path
    {
        freedup(GB_MAIN(gb)->path, path);
    }
    return GB_save_as(gb, path, savetype);
}

GB_ERROR GB_create_parent_directory(const char *path) {
    GB_ERROR error = NULL;
    char *parent;
    GB_split_full_path(path, &parent, NULL, NULL, NULL);
    if (parent) {
        if (!GB_is_directory(parent)) error = GB_create_directory(parent);
        free(parent);
    }
    return error;
}

GB_ERROR GB_create_directory(const char *path) {
    GB_ERROR error = 0;
    if (!GB_is_directory(path)) {
        error = GB_create_parent_directory(path);
        if (!error) {
            int res = mkdir(path, ACCESSPERMS);
            if (res) error = GB_IO_error("creating directory", path);
        }
        error = GB_failedTo_error("GB_create_directory", path, error);
    }
    return error;
}

GB_ERROR GB_save_in_arbprop(GBDATA *gb, const char *path, const char *savetype) {
    /* savetype
     *      'a'    ascii
     *      'b'    binary
     *      'bm'   binary + mapfile
     *
     * automatically creates subdirectories
     */

    char     *fullname = strdup(GB_path_in_arbprop(path ? path : GB_MAIN(gb)->path));
    GB_ERROR  error    = GB_create_parent_directory(fullname);
    if (!error) error = GB_save_as(gb, fullname, savetype);
    free(fullname);

    return error;
}

GB_ERROR GB_MAIN_TYPE::check_saveable(const char *new_path, const char *flags) const {
    /* Check wether file can be stored at destination
     *  'f' in flags means 'force' => ignores main->disabled_path
     *  'q' in flags means 'quick save'
     *  'n' in flags means destination must be empty
     */

    GB_ERROR error = NULL;
    if (is_client()) {
        error = "You cannot save a remote database,\nplease use save button in master program";
    }
    else if (opentype == gb_open_read_only_all) {
        error = "Database is read only";
    }
    else if (strchr(new_path, ':')) {
        error = "Your database name may not contain a ':' character\nChoose a different name";
    }
    else {
        char *fullpath = gb_full_path(new_path);
        if (disabled_path && !strchr(flags, 'f')) {
            if (GBS_string_matches(fullpath, disabled_path, GB_MIND_CASE)) {
                error = GBS_global_string("You are not allowed to save your database in this directory,\n"
                                          "Please select 'save as' and save your data to a different location");
            }
        }

        if (!error) {
            // check whether destination directory exists
            char *lslash = strrchr(fullpath, '/');
            if (lslash) {
                lslash[0] = 0;
                if (!GB_is_directory(fullpath)) {
                    error = GBS_global_string("Directory '%s' doesn't exist", fullpath);
                }
                lslash[0] = '/';
            }
        }
        free(fullpath);
    }
    
    if (!error && !strchr(flags, 'q')) {
        long mode = GB_mode_of_link(new_path);
        if (mode >= 0 && !(mode & S_IWUSR)) { // no write access -> looks like a master file
            error = GBS_global_string("Your selected file '%s'\n"
                                      "already exists and is write protected!\n"
                                      "This happens e.g. if your file is a MASTER ARB FILE which is\n"
                                      "used by multiple quicksaved databases.\n"
                                      "If you want to save it nevertheless, delete it first, but\n"
                                      "note that doing this will render all these quicksaves useless!",
                                      new_path);
        }
    }
    
    if (!error && strchr(flags, 'n') && GB_time_of_file(new_path)) {
        error = GBS_global_string("Your destination file '%s' already exists.\n"
                                  "Delete it manually!", new_path);
    }

#if (MEMORY_TEST==1)
    if (!error && strchr(flags, 'm')) {
        error = "It's impossible to save mapfiles (ARBDB is MEMORY_TEST mode 1)";
    }
#endif

    return error;
}

static GB_ERROR protect_corruption_error(const char *savepath) {
    GB_ERROR error = NULL;
    gb_assert(seen_corrupt_data);
    if (strstr(savepath, "CORRUPTED") == 0) {
        error = "Severe error: Corrupted data detected during save\n"
            "ARB did NOT save your database!\n"
            "Advices:\n"                                                    //|
            "* If your previous (quick)save was not long ago, your savest\n"
            "  option is to drop the changes since then, by reloading the not\n"
            "  corrupted database and redo your changes. If you can reproduce\n"
            "  the bug that corrupted the entries, please report it!\n"
            "* If that is no option (because too much work would be lost)\n"
            "  you can force saving the corrupted database by adding the text\n"
            "  'CORRUPTED' to the database name. After doing that, do NOT\n"
            "  quit ARB, instead try to find and fix all corrupted entries\n"
            "  that were listed below. Manually enter their original values\n"
            "  (in case you want to lookup or copy&paste some values, you may\n"
            "   open the last saved version of this database using\n"
            "   'Start second database').\n"
            "  Saving the database again will show all remaining unfixed\n"
            "  entries. If no more corrupted entries show up, you can safely\n"
            "  continue to work with that database.";
    }
    else {
        GB_warning("Warning: Saved corrupt database");
    }
    seen_corrupt_data = false;
    return error;
}

GB_ERROR GB_MAIN_TYPE::save_as(const char *as_path, const char *savetype) {
    GB_ERROR error = 0;

    bool saveASCII                            = false;
    if (strchr(savetype, 'a')) saveASCII      = true;
    else if (strchr(savetype, 'b')) saveASCII = false;
    else error                                = GBS_global_string("Invalid savetype '%s' (expected 'a' or 'b')", savetype);

    if (!error) {
        if (!as_path) as_path              = path;
        if (!as_path || !as_path[0]) error = "Please specify a savename";
        else error                         = check_saveable(as_path, savetype);
    }

    if (!error) {
        char *mappath        = NULL;
        char *sec_path       = strdup(gb_overwriteName(as_path));
        char *sec_mappath    = NULL;
        bool  dump_to_stdout = strchr(savetype, 'S');
        FILE *out            = dump_to_stdout ? stdout : fopen(sec_path, "w");

        if (!out) error = GB_IO_error("saving", sec_path);
        else {
            const int org_security_level    = security_level;
            const int org_transaction_level = get_transaction_level();

            if (!org_transaction_level) transaction_level = 1;
            else {
                if (org_transaction_level> 0) {
                    GB_commit_transaction(root_container);
                    GB_begin_transaction(root_container);
                }
            }
            security_level    = 7;
            seen_corrupt_data = false;

            bool outOfOrderSave     = strchr(savetype, 'f');
            bool deleteQuickAllowed = !outOfOrderSave && !dump_to_stdout;
            {
                int result = 0;

                if (saveASCII) {
                    fprintf(out, "/*ARBDB ASCII*/\n");
                    gb_write_rek(out, root_container, 0, 1);
                    freedup(qs.quick_save_disabled, "Database saved in ASCII mode");
                    if (deleteQuickAllowed) error = gb_remove_all_but_main(this, as_path);
                }
                else {                      // save binary
                    mappath = strdup(gb_mapfile_name(as_path));
                    if (strchr(savetype, 'm')) {
                        // it's necessary to save the mapfile FIRST,
                        // cause this re-orders all GB_CONTAINERs containing NULL-entries in their header
                        sec_mappath = strdup(gb_overwriteName(mappath));
                        error       = gb_save_mapfile(this, sec_mappath);
                    }
                    else GB_unlink_or_warn(mappath, &error); // delete old mapfile
                    if (!error) result |= gb_write_bin(out, root_container, 1);
                }

                security_level    = org_security_level;
                transaction_level = org_transaction_level;

                if (!dump_to_stdout) result |= fclose(out);
                if (result != 0) error       = GB_IO_error("writing", sec_path);
            }

            if (!error && seen_corrupt_data) {
                error = protect_corruption_error(as_path);
            }

            if (!error && !saveASCII) {
                if (!outOfOrderSave) freenull(qs.quick_save_disabled); // delete reason, why quicksaving was disallowed
                if (deleteQuickAllowed) error = gb_remove_quick_saved(this, as_path);
            }

            if (!dump_to_stdout) {
                if (error) {
                    if (sec_mappath) GB_unlink_or_warn(sec_mappath, NULL);
                    GB_unlink_or_warn(sec_path, NULL);
                }
                else {
                    bool unlinkMapfiles       = false;
                    error                     = GB_rename_file(sec_path, as_path);
                    if (error) unlinkMapfiles = true;
                    else if (sec_mappath) {
                        error             = GB_rename_file(sec_mappath, mappath);
                        if (!error) error = GB_set_mode_of_file(mappath, GB_mode_of_file(as_path)); // set mapfile to same mode ...
                        if (!error) error = GB_set_time_of_file(mappath, GB_time_of_file(as_path)); // ... and same time as DB file
                        if (error) {
                            GB_warningf("Error: %s\n[Falling back to non-fastload-save]", error);
                            error          = 0;
                            unlinkMapfiles = true;
                        }
                    }

                    if (unlinkMapfiles) {
                        GB_unlink_or_warn(sec_mappath, NULL);
                        GB_unlink_or_warn(mappath, NULL);
                    }
                            
                    if (!error) {
                        error = qs.quick_save_disabled == 0
                            ? gb_create_reference(as_path)
                            : gb_delete_reference(as_path);
                    }
                }
            }

            if (!error && !outOfOrderSave) {
                last_saved_transaction      = GB_read_clock(root_container);
                last_main_saved_transaction = GB_read_clock(root_container);
                last_saved_time             = GB_time_of_day();
            }
        }

        free(sec_path);
        free(mappath);
        free(sec_mappath);
    }
    return error;
}

GB_ERROR GB_save_as(GBDATA *gbd, const char *path, const char *savetype) {
    /* Save whole database
     *
     * savetype
     *          'a' ascii
     *          'b' binary
     *          'm' save mapfile (only together with binary)
     *          'f' force saving even in disabled path to a different directory (out of order save)
     *          'S' save to stdout (for debugging)
     */

    GB_ERROR error = NULL;

    gb_assert(savetype);

    if (!gbd) {
        error = "got no DB";
    }
    else {
        error = GB_MAIN(gbd)->save_as(path, savetype);
    }

    RETURN_ERROR(error);
}

GB_ERROR GB_MAIN_TYPE::check_quick_save() const {
    /* is quick save allowed?
     * return NULL if allowed, error why disallowed otherwise.
     */

    if (qs.quick_save_disabled) {
        return GBS_global_string("Save Changes Disabled, because\n"
                                 "    '%s'\n"
                                 "    Save whole database using binary mode first",
                                 qs.quick_save_disabled);
    }
    return NULL;
}

GB_ERROR GB_delete_database(GB_CSTR filename) {
    GB_ERROR error = 0;

    if (GB_unlink(filename)<0) error = GB_await_error();
    else error                       = gb_remove_all_but_main(0, filename);

    return error;
}

GB_ERROR GB_MAIN_TYPE::save_quick_as(const char *as_path) {
    GB_ERROR error = NULL;
    if (!as_path || !strlen(as_path)) {
        error = "Please specify a file name";
    }
    else if (strcmp(as_path, path) == 0) {    // same name (no rename)
        error = save_quick(as_path);
    }
    else {
        error = check_quick_saveable(as_path, "bn");

        if (!error) {
            FILE *fmaster = fopen(path, "r");         // old master !!!!
            if (!fmaster) {                                 // Oh no, where is my old master
                error = GBS_global_string("Save Changes is missing master ARB file '%s',\n"
                                          "    save database first", path);
            }
            else {
                fclose(fmaster);
            }
        }
        if (!error) {
            if (GB_unlink(as_path)<0) { // delete old file
                error = GBS_global_string("File '%s' already exists and could not be deleted\n"
                                          "(Reason: %s)",
                                          as_path, GB_await_error());
            }
        }
        if (!error) {
            char *org_master = S_ISLNK(GB_mode_of_link(path))
                ? GB_follow_unix_link(path)
                : strdup(path);

            error = gb_remove_all_but_main(this, as_path);
            if (!error) {
                long mode = GB_mode_of_file(org_master);
                if (mode & S_IWUSR) {
                    GB_ERROR sm_error = GB_set_mode_of_file(org_master, mode & ~(S_IWUSR | S_IWGRP | S_IWOTH));
                    if (sm_error) {
                        GB_warningf("%s\n"
                                    "Ask your admin to remove write permissions from that master file.\n"
                                    "NEVER delete or change it, otherwise your quicksaves will be rendered useless!", 
                                    sm_error);
                    }
                }
                char *full_path_of_source;
                if (strchr(as_path, '/') || strchr(org_master, '/')) {
                    // dest or source in different directory
                    full_path_of_source = gb_full_path(org_master);
                }
                else {
                    full_path_of_source = strdup(org_master);
                }

                error = GB_symlink(full_path_of_source, as_path);
                if (!error) {
                    if ((uid_t)GB_getuid_of_file(full_path_of_source) != getuid()) {
                        GB_warningf("**** WARNING ******\n"
                                    "   You now using a file '%s'\n"
                                    "   which is owned by another user\n"
                                    "   Please ask him not to delete this file\n"
                                    "   If you don't trust him, don't save changes but\n"
                                    "   the WHOLE database", full_path_of_source);
                    }

                    GB_ERROR warning = gb_add_reference(full_path_of_source, as_path);
                    if (warning) GB_warning(warning);

                    freedup(path, as_path);                      // Symlink created -> rename allowed

                    qs.last_index = -1; // Start with new quicks (next index will be 0)
                    error = save_quick(as_path);
                }
                free(full_path_of_source);
            }
            free(org_master);
        }
    }

    RETURN_ERROR(error);
}

GB_ERROR GB_save_quick_as(GBDATA *gbd, const char *path) {
    return GB_MAIN(gbd)->save_quick_as(path);
}

GB_ERROR GB_MAIN_TYPE::save_quick(const char *refpath) {
    GB_ERROR error = check_quick_saveable(refpath, "q");

    if (!error && refpath && strcmp(refpath, path) != 0) {
        error = GBS_global_string("master file rename '%s'!= '%s',\n"
                                  "save database first", refpath, path);
    }
    if (!error) {
        FILE *fmaster = fopen(path, "r");

        if (!fmaster) {
            error = GBS_global_string("Quick save is missing master ARB file '%s',\n"
                                      "save database first", refpath);
        }
        else {
            fclose(fmaster);
        }
    }
    if (!error && is_client()) error = "You cannot save a remote database";
    if (!error) {
        qs.last_index++;
        if (qs.last_index > GB_MAX_QUICK_SAVE_INDEX) renameQuicksaves(this);

        GB_CSTR qck_path = gb_quicksaveName(path, qs.last_index);
        GB_CSTR sec_path = gb_overwriteName(qck_path);

        FILE *out       = fopen(sec_path, "w");
        if (!out) error = GBS_global_string("Cannot save file to '%s'", sec_path);
        else {
            long erg;
            {
                const int org_security_level    = security_level;
                int       org_transaction_level = get_transaction_level();

                if (!org_transaction_level) transaction_level = 1;
                else {
                    if (org_transaction_level> 0) {
                        GB_commit_transaction(root_container);
                        GB_begin_transaction(root_container);
                    }
                }

                security_level    = 7;
                seen_corrupt_data = false;

                erg = gb_write_bin(out, root_container, 2);

                security_level    = org_security_level;
                transaction_level = org_transaction_level;
            }

            erg |= fclose(out);

            if (erg!=0) error = GBS_global_string("Cannot write to '%s'", sec_path);
            else {
                if (seen_corrupt_data) {
                    gb_assert(!error);
                    error = protect_corruption_error(qck_path);
                }
                if (!error) error = GB_rename_file(sec_path, qck_path);
                if (error) GB_unlink_or_warn(sec_path, NULL);
            }
        }

        if (error) qs.last_index--; // undo index increment
        else {
            last_saved_transaction = GB_read_clock(root_container);
            last_saved_time        = GB_time_of_day();

            error = deleteSuperfluousQuicksaves(this);
        }
    }

    RETURN_ERROR(error);
}

GB_ERROR GB_save_quick(GBDATA *gbd, const char *refpath) {
    return GB_MAIN(gbd)->save_quick(refpath);
}


void GB_disable_path(GBDATA *gbd, const char *path) {
    // disable directories for save
    freeset(GB_MAIN(gbd)->disabled_path, path ? GBS_eval_env(path) : NULL);
}

long GB_last_saved_clock(GBDATA *gb_main) {
    return GB_MAIN(gb_main)->last_saved_transaction;
}

GB_ULONG GB_last_saved_time(GBDATA *gb_main) {
    return GB_MAIN(gb_main)->last_saved_time;
}

// --------------------------------------------------------------------------------

#ifdef UNIT_TESTS

#include <test_unit.h>

#define SAVE_AND_COMPARE(gbd, save_as, savetype, compare_with) \
    TEST_EXPECT_NO_ERROR(GB_save_as(gbd, save_as, savetype));  \
    TEST_EXPECT_FILES_EQUAL(save_as, compare_with)

static GB_ERROR modify_db(GBDATA *gb_main) {
    GB_transaction ta(gb_main);

    GB_ERROR  error          = NULL;
    GBDATA   *gb_container   = GB_create_container(gb_main, "container");
    if (!gb_container) error = GB_await_error();
    else {
        GBDATA *gb_entry     = GB_create(gb_container, "str", GB_STRING);
        if (!gb_entry) error = GB_await_error();
        else    error        = GB_write_string(gb_entry, "text");
        // else    error        = GB_write_string(gb_entry, "bla"); // provoke error in file compare
    }
    return error;
}

// #define TEST_AUTO_UPDATE // uncomment to auto-update binary and quicksave testfiles (needed once after changing ascii testfile or modify_db())

#define TEST_loadsave_CLEANUP() TEST_EXPECT_ZERO(system("rm -f [ab]2[ab]*.* master.* slave.* renamed.* fast.* fast2b.* TEST_loadsave.ARF"))

void TEST_SLOW_loadsave() {
    GB_shell shell;
    TEST_loadsave_CLEANUP();

    // test non-existing DB
    TEST_EXPECT_NORESULT__ERROREXPORTED_CONTAINS(GB_open("nonexisting.arb", "r"), "'nonexisting.arb' not found");
    TEST_EXPECT_NORESULT__ERROREXPORTED_CONTAINS(GB_open("nonexisting.arb", "rw"), "'nonexisting.arb' not found");
    {
        GBDATA *gb_new;
        TEST_EXPECT_RESULT__NOERROREXPORTED(gb_new = GB_open("nonexisting.arb", "w")); // create new DB
        GB_close(gb_new);
    }

    // the following DBs have to be provided in directory ../UNIT_TESTER/run
    const char *bin_db = "TEST_loadsave.arb";
    const char *asc_db = "TEST_loadsave_ascii.arb";

    GBDATA *gb_asc;
    TEST_EXPECT_RESULT__NOERROREXPORTED(gb_asc = GB_open(asc_db, "rw"));

#if defined(TEST_AUTO_UPDATE)
    TEST_EXPECT_NO_ERROR(GB_save_as(gb_asc, bin_db, "b"));
#endif // TEST_AUTO_UPDATE

    GBDATA *gb_bin;
    TEST_EXPECT_RESULT__NOERROREXPORTED(gb_bin = GB_open(bin_db, "rw"));

    // test ASCII / BINARY compatibility
    SAVE_AND_COMPARE(gb_asc, "a2a.arb", "a", asc_db);
    SAVE_AND_COMPARE(gb_asc, "a2b.arb", "b", bin_db);
    SAVE_AND_COMPARE(gb_bin, "b2a.arb", "a", asc_db);
    SAVE_AND_COMPARE(gb_bin, "b2b.arb", "b", bin_db);

#if (MEMORY_TEST == 0)
    {
        GBDATA *gb_nomap;
        TEST_EXPECT_RESULT__NOERROREXPORTED(gb_nomap = GB_open(bin_db, "rw"));
        TEST_EXPECT_NO_ERROR(GB_save_as(gb_nomap, "fast.arb", "bm"));
        TEST_EXPECT(GB_is_regularfile("fast.ARM")); // assert map file has been saved
        TEST_EXPECT_EQUAL(GB_time_of_file("fast.ARM"), GB_time_of_file("fast.arb"));
        GB_close(gb_nomap);
    }
    {
        // open DB with mapfile
        GBDATA *gb_map;
        TEST_EXPECT_RESULT__NOERROREXPORTED(gb_map = GB_open("fast.arb", "rw"));
        SAVE_AND_COMPARE(gb_map, "fast2b.arb", "b", bin_db);
        GB_close(gb_map);
    }
    {
        // test alloc/free (no real test, just call it for code coverage)
        char *small_block = (char*)gbm_get_mem(30, 5);
        gbm_free_mem(small_block, 30, 5);

        char *big_block = (char*)gbm_get_mem(3000, 6);
        gbm_free_mem(big_block, 3000, 6);
    }
#endif

    {
        // test opening saved DBs
        GBDATA *gb_a2b = GB_open("a2b.arb", "rw"); TEST_REJECT_NULL(gb_a2b);
        GBDATA *gb_b2b = GB_open("b2b.arb", "rw"); TEST_REJECT_NULL(gb_b2b);

        // modify ..
        TEST_EXPECT_NO_ERROR(modify_db(gb_a2b));
        TEST_EXPECT_NO_ERROR(modify_db(gb_b2b));

        // .. and quicksave
        TEST_EXPECT_NO_ERROR(GB_save_quick(gb_a2b, "a2b.arb"));
        TEST_EXPECT_NO_ERROR(GB_save_quick(gb_b2b, "b2b.arb"));

#if defined(TEST_AUTO_UPDATE)
        TEST_COPY_FILE("a2b.a00", "TEST_loadsave_quick.a00");
#endif // TEST_AUTO_UPDATE

        TEST_EXPECT_FILES_EQUAL("TEST_loadsave_quick.a00", "a2b.a00");
        TEST_EXPECT_FILES_EQUAL("a2b.a00", "b2b.a00");

        TEST_EXPECT_NO_ERROR(GB_save_quick_as(gb_a2b, "a2b.arb"));

        // check wether quicksave can be disabled
        GB_disable_quicksave(gb_a2b, "test it");

        TEST_EXPECT_ERROR_CONTAINS(GB_save_quick(gb_a2b, "a2b.arb"), "Save Changes Disabled");
        TEST_EXPECT_ERROR_CONTAINS(GB_save_quick_as(gb_a2b, "a2b.arb"), "Save Changes Disabled");

        const char *mod_db = "a2b_modified.arb";
        TEST_EXPECT_NO_ERROR(GB_save_as(gb_a2b, mod_db, "b")); // save modified DB
        // test loading quicksave
        {
            GBDATA *gb_quicksaved = GB_open("a2b.arb", "rw"); // this DB has a quicksave
            SAVE_AND_COMPARE(gb_quicksaved, "a2b.arb", "b", mod_db);
            GB_close(gb_quicksaved);
        }

        {
            // check master/slave DBs
            TEST_EXPECT_NO_ERROR(GB_save_as(gb_b2b, "master.arb", "b"));

            GBDATA *gb_master = GB_open("master.arb", "rw"); TEST_REJECT_NULL(gb_master);
            TEST_EXPECT_NO_ERROR(modify_db(gb_master));

            TEST_EXPECT_NO_ERROR(GB_save_quick(gb_master, "master.arb"));
            TEST_EXPECT_NO_ERROR(GB_save_quick_as(gb_master, "master.arb"));

            TEST_EXPECT_ERROR_CONTAINS(GB_save_quick(gb_master, "renamed.arb"), "master file rename"); // quicksave with wrong name

            // check if master gets protected by creating slave-DB
            TEST_EXPECT_NO_ERROR(GB_save_as(gb_master, "master.arb", "b")); // overwrite
            TEST_EXPECT_NO_ERROR(GB_save_quick_as(gb_master, "slave.arb")); // create slave -> master now protected
            TEST_EXPECT_ERROR_CONTAINS(GB_save_as(gb_master, "master.arb", "b"), "already exists and is write protected"); // overwrite should fail now

            {
                GBDATA *gb_slave = GB_open("slave.arb", "rw"); TEST_REJECT_NULL(gb_slave); // load slave DB
                TEST_EXPECT_NO_ERROR(modify_db(gb_slave));
                TEST_EXPECT_NO_ERROR(GB_save_quick(gb_slave, "slave.arb"));
                TEST_EXPECT_NO_ERROR(GB_save_quick_as(gb_slave, "renamed.arb"));
                GB_close(gb_slave);
            }
            GB_close(gb_master);
        }

        // test various error conditions:

        TEST_EXPECT_ERROR_CONTAINS(GB_save_as(gb_b2b, "", "b"), "specify a savename"); // empty name

        TEST_EXPECT_NO_ERROR(GB_set_mode_of_file(mod_db, 0444)); // write-protect
        TEST_EXPECT_ERROR_CONTAINS(GB_save_as(gb_b2b, mod_db, "b"), "already exists and is write protected"); // try to overwrite write-protected DB

        TEST_EXPECT_ERROR_CONTAINS(GB_save_quick_as(gb_b2b, NULL), "specify a file name"); // no name
        TEST_EXPECT_ERROR_CONTAINS(GB_save_quick_as(gb_b2b, ""), "specify a file name"); // empty name

        GB_close(gb_b2b);
        GB_close(gb_a2b);
    }

    GB_close(gb_asc);
    GB_close(gb_bin);

    TEST_loadsave_CLEANUP();
}

#define TEST_quicksave_CLEANUP() TEST_EXPECT_ZERO(system("rm -f min_bin.a[0-9]* min_bin.ARF"))

inline bool quicksave_exists(int i) {
    const char *qsformat = "min_bin.a%02i";
    return GB_is_regularfile(GBS_global_string(qsformat, (i)));
}
inline bool quicksave_missng(int i)          { return !quicksave_exists(i); }
inline bool is_first_quicksave(int i)        { return quicksave_exists(i) && !quicksave_exists(i-1); }
inline bool is_last_quicksave(int i)         { return quicksave_exists(i) && !quicksave_exists(i+1); }
inline bool quicksaves_range(int from, int to) { return is_first_quicksave(from) && is_last_quicksave(to); }

#define TEST_QUICK_RANGE(s,e) TEST_EXPECT(quicksaves_range(s,e))
#define TEST_QUICK_GONE(i)    TEST_EXPECT(quicksave_missng(i))

void TEST_SLOW_quicksave_names() {
    // check quicksave delete and wrap around
    TEST_quicksave_CLEANUP();
    const char *bname = "min_bin.arb";

    GB_shell shell;
    
#if 0
    {
        // update min_bin.arb from min_ascii.arb
        const char *aname    = "min_ascii.arb";
        GBDATA     *gb_ascii = GB_open(aname, "rw"); TEST_REJECT_NULL(gb_ascii);

        TEST_EXPECT_NO_ERROR(GB_save_as(gb_ascii, bname, "b"));
        GB_close(gb_ascii);
    }
#endif
    GBDATA *gb_bin = GB_open(bname, "rw"); TEST_REJECT_NULL(gb_bin);
    for (int i = 0; i <= 100; ++i) {
        TEST_EXPECT_NO_ERROR(GB_save_quick(gb_bin, bname));
        switch (i) {
            case  0: TEST_QUICK_RANGE( 0,  0); break;
            case  1: TEST_QUICK_RANGE( 0,  1); break;
            case 10: TEST_QUICK_RANGE( 1, 10); break;
            case 98: TEST_QUICK_RANGE(89, 98); break;
            case 99: TEST_QUICK_RANGE(90, 99);
                TEST_QUICK_GONE(0);    // should not exist yet
                break;
            case 100: TEST_QUICK_RANGE(0, 9);
                TEST_QUICK_GONE((i-8));
                TEST_QUICK_GONE((i-1));
                TEST_QUICK_GONE(i);
                break;
        }
        if (i == 10) {
            // speed-up-hack
            GB_MAIN_TYPE *Main   = GB_MAIN(gb_bin);
            i                   += 78; // -> 88 (afterwards run 10 times w/o checks to fake correct state)
            Main->qs.last_index += 78;
        }
    }

    GB_close(gb_bin);
    
    TEST_quicksave_CLEANUP();
}

void TEST_db_filenames() {
    TEST_EXPECT_EQUAL(gb_quicksaveName("nosuch.arb", 0), "nosuch.a00");
    TEST_EXPECT_EQUAL(gb_quicksaveName("nosuch", 1), "nosuch.a01");
}

void TEST_SLOW_corruptedEntries_saveProtection() {
    // see #499 and #501
    GB_shell shell;

    const char *name_NORMAL[] = {
        "corrupted.arb",
        "corrupted2.arb",
    };
    const char *name_CORRUPTED[] = {
        "corrupted_CORRUPTED.arb",
        "corrupted2_CORRUPTED.arb",
    };

    const char *quickname           = "corrupted.a00";
    const char *quickname_CORRUPTED = "corrupted_CORRUPTED.a00";
    const char *quickname_unwanted  = "corrupted_CORRUPTED.a01";

    const char **name = name_NORMAL;

    const char *INITIAL_VALUE = "initial value";
    const char *CHANGED_VALUE = "changed";

    GB_unlink("*~");
    GB_unlink(quickname_unwanted);

    for (int corruption = 0; corruption<=3; ++corruption) {
        TEST_ANNOTATE(GBS_global_string("corruption level %i", corruption));

        GB_unlink(name[0]);

        // create simple DB
        {
            GBDATA *gb_main = GB_open(name[0], "cwr");
            TEST_REJECT_NULL(gb_main);

            {
                GB_transaction ta(gb_main);

                GBDATA *gb_entry = GB_create(gb_main, "sth", GB_STRING);
                TEST_REJECT_NULL(gb_entry);
                TEST_EXPECT_NO_ERROR(GB_write_string(gb_entry, INITIAL_VALUE));

                GBDATA *gb_other = GB_create(gb_main, "other", GB_INT);
                TEST_REJECT_NULL(gb_other);
                TEST_EXPECT_NO_ERROR(GB_write_int(gb_other, 4711));
            }

            TEST_EXPECT_NO_ERROR(GB_save(gb_main, NULL, "b"));
            GB_close(gb_main);
        }

        // reopen DB, change the entry, quick save + full save with different name
        {
            GBDATA *gb_main = GB_open(name[0], "wr");
            TEST_REJECT_NULL(gb_main);

            {
                GB_transaction ta(gb_main);

                GBDATA *gb_entry = GB_entry(gb_main, "sth");
                TEST_REJECT_NULL(gb_entry);

                const char *content = GB_read_char_pntr(gb_entry);
                TEST_EXPECT_EQUAL(content, INITIAL_VALUE);

                TEST_EXPECT_NO_ERROR(GB_write_string(gb_entry, CHANGED_VALUE));

                content = GB_read_char_pntr(gb_entry);
                TEST_EXPECT_EQUAL(content, CHANGED_VALUE);

                // now corrupt the DB entry:
                if (corruption>0) {
                    char *illegal_access = (char*)content;
                    illegal_access[2]    = 0;

                    if (corruption>1) {
                        gb_entry = GB_create(gb_main, "sth", GB_STRING);
                        TEST_REJECT_NULL(gb_entry);
                        TEST_EXPECT_NO_ERROR(GB_write_string(gb_entry, INITIAL_VALUE));

                        if (corruption>2) {
                            // fill rest of string with zero bytes (similar to copying a truncated string into calloced memory)
                            int len = strlen(CHANGED_VALUE);
                            for (int i = 3; i<len; ++i) {
                                illegal_access[i] = 0;
                            }
                        }
                    }

// #define PERFORM_DELETE
#ifdef PERFORM_DELETE
                    // delete "other"
                    GBDATA *gb_other = GB_entry(gb_main, "other");
                    TEST_REJECT_NULL(gb_other);
                    TEST_EXPECT_NO_ERROR(GB_delete(gb_other));
#endif
                }
            }

            GB_ERROR quick_error = GB_save_quick(gb_main, name[0]);
            TEST_REJECT(seen_corrupt_data);
            if (corruption) {
                TEST_EXPECT_CONTAINS(quick_error, "Corrupted data detected during save");
                quick_error = GB_save_quick_as(gb_main, name_CORRUPTED[0]); // save with special name (as user should do)
                TEST_REJECT(seen_corrupt_data);
            }
            TEST_REJECT(quick_error);

            GB_ERROR full_error = GB_save(gb_main, name[1], "b");
            TEST_REJECT(seen_corrupt_data);
            if (corruption) {
                TEST_EXPECT_CONTAINS(full_error, "Corrupted data detected during save");
                full_error  = GB_save(gb_main, name_CORRUPTED[1], "b"); // save with special name (as user should do)
                TEST_REJECT(seen_corrupt_data);
                name = name_CORRUPTED; // from now on use these names (for load and save)
            }
            TEST_REJECT(full_error);

            GB_close(gb_main);
        }

        for (int full = 0; full<2; ++full) {
            TEST_ANNOTATE(GBS_global_string("corruption level %i / full=%i", corruption, full));

            // reopen DB (full==0 -> load quick save; ==1 -> load full save)
            GBDATA *gb_main = GB_open(name[full], "r");
            TEST_REJECT_NULL(gb_main);

            if (gb_main) {
                {
                    GB_transaction ta(gb_main);

                    GBDATA *gb_entry = GB_entry(gb_main, "sth");
                    TEST_REJECT_NULL(gb_entry);

                    const char *content = GB_read_char_pntr(gb_entry);

                    switch (corruption) {
                        case 0:
                            TEST_EXPECT_EQUAL(content, CHANGED_VALUE);
                            break;
                        default:
                            TEST_EXPECT_EQUAL(content, "ch");
                            break;
                    }

                    // check 2nd entry
                    gb_entry = GB_nextEntry(gb_entry);
                    if (corruption>1) {
                        TEST_REJECT_NULL(gb_entry);

                        content = GB_read_char_pntr(gb_entry);
                        TEST_EXPECT_EQUAL(content, INITIAL_VALUE);
                    }
                    else {
                        TEST_REJECT(gb_entry);
                    }

                    // check int entry
                    GBDATA *gb_other = GB_entry(gb_main, "other");
#if defined(PERFORM_DELETE)
                    bool    deleted  = corruption>0;
#else // !defined(PERFORM_DELETE)
                    bool    deleted  = false;
#endif

                    if (deleted) {
                        TEST_REJECT(gb_other);
                    }
                    else {
                        TEST_REJECT_NULL(gb_other);
                        TEST_EXPECT_EQUAL(GB_read_int(gb_other), 4711);
                    }
                }

                GB_close(gb_main);
            }
            GB_unlink(name_NORMAL[full]);
            GB_unlink(name_CORRUPTED[full]);
        }
        GB_unlink(quickname);
        GB_unlink(quickname_CORRUPTED);

        TEST_REJECT(GB_is_regularfile(quickname_unwanted));

        name = name_NORMAL; // restart with normal names
    }
}

#endif // UNIT_TESTS