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

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#ifdef HAVE_ALLOCA_H
# include <alloca.h>
#elif defined __GNUC__
# define alloca __builtin_alloca
#elif defined _AIX
# define alloca __alloca
#elif defined _MSC_VER
# include <malloc.h>
# define alloca _alloca
#else
# include <stddef.h>
# ifdef  __cplusplus
extern "C"
# endif
void *alloca (size_t);
#endif

#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <time.h>
#include <string.h>
#include <fnmatch.h>
#include <fcntl.h>
#include <unistd.h>
#include <zlib.h>

#ifdef HAVE_NETINET_IN_H
# include <netinet/in.h>
#endif

#if defined(_WIN32) && ! defined(__CEGCC__)
# include <winsock2.h>
#endif

#ifdef HAVE_EVIL
# include <Evil.h>
#endif

#include "Eet.h"
#include "Eet_private.h"

#ifdef HAVE_REALPATH
#undef HAVE_REALPATH
#endif

#define EET_MAGIC_FILE                  0x1ee7ff00
#define EET_MAGIC_FILE_HEADER           0x1ee7ff01

#define EET_MAGIC_FILE2                 0x1ee70f42

typedef struct _Eet_File_Header         Eet_File_Header;
typedef struct _Eet_File_Node           Eet_File_Node;
typedef struct _Eet_File_Directory      Eet_File_Directory;

struct _Eet_File
{
   char                 *path;
   FILE                 *fp;
   FILE			*readfp;
   Eet_File_Header      *header;
   const unsigned char  *data;
   Eet_Dictionary       *ed;

   int                   magic;
   int                   references;

   Eet_File_Mode         mode;
   int                   data_size;
   time_t                mtime;

   unsigned char         writes_pending : 1;
   unsigned char         delete_me_now : 1;
};

struct _Eet_File_Header
{
   int                 magic;
   Eet_File_Directory *directory;
};

struct _Eet_File_Directory
{
   int             size;
   Eet_File_Node **nodes;
};

struct _Eet_File_Node
{
   char                 *name;
   void                 *data;
   Eet_File_Node        *next; /* FIXME: make buckets linked lists */

   int                   offset;
   int                   dictionary_offset;
   int                   name_offset;

   int                   name_size;
   int                   size;
   int                   data_size;

   unsigned char         free_name : 1;
   unsigned char         compression : 1;
};

#if 0
/* Version 2 */
/* NB: all int's are stored in network byte order on disk */
/* file format: */
int magic; /* magic number ie 0x1ee7ff00 */
int num_directory_entries; /* number of directory entries to follow */
int bytes_directory_entries; /* bytes of directory entries to follow */
struct
{
   int offset; /* bytes offset into file for data chunk */
   int flags; /* flags - for now 0 = uncompressed, 1 = compressed */
   int size; /* size of the data chunk */
   int data_size; /* size of the (uncompressed) data chunk */
   int name_size; /* length in bytes of the name field */
   char name[name_size]; /* name string (variable length) and \0 terminated */
} directory[num_directory_entries];
/* and now startes the data stream... */
#endif

#if 0
/* Version 3 */
/* NB: all int's are stored in network byte order on disk */
/* file format: */
int magic; /* magic number ie 0x1ee70f42 */
int num_directory_entries; /* number of directory entries to follow */
int num_dictionary_entries; /* number of dictionary entries to follow */
struct
{
  int data_offset; /* bytes offset into file for data chunk */
  int size; /* size of the data chunk */
  int data_size; /* size of the (uncompressed) data chunk */
  int name_offset; /* bytes offset into file for name string */
  int name_size; /* length in bytes of the name field */
  int flags; /* flags - for now 0 = uncompressed, 1 = compressed */
} directory[num_directory_entries];
struct
{
  int hash;
  int offset;
  int size;
  int prev;
  int next;
} dictionary[num_dictionary_entries];
/* now start the string stream. */
/* and right after them the data stream. */
#endif

#define EET_FILE2_HEADER_COUNT                  3
#define EET_FILE2_DIRECTORY_ENTRY_COUNT         6
#define EET_FILE2_DICTIONARY_ENTRY_COUNT        5

#define EET_FILE2_HEADER_SIZE                   (sizeof(int) * EET_FILE2_HEADER_COUNT)
#define EET_FILE2_DIRECTORY_ENTRY_SIZE          (sizeof(int) * EET_FILE2_DIRECTORY_ENTRY_COUNT)
#define EET_FILE2_DICTIONARY_ENTRY_SIZE         (sizeof(int) * EET_FILE2_DICTIONARY_ENTRY_COUNT)

/* prototypes of internal calls */
static Eet_File		*eet_cache_find(const char *path, Eet_File **cache, int cache_num);
static void		eet_cache_add(Eet_File *ef, Eet_File ***cache, int *cache_num, int *cache_alloc);
static void		eet_cache_del(Eet_File *ef, Eet_File ***cache, int *cache_num, int *cache_alloc);
static int		eet_string_match(const char *s1, const char *s2);
#if 0 /* Unused */
static Eet_Error	eet_flush(Eet_File *ef);
#endif
static Eet_Error	eet_flush2(Eet_File *ef);
static Eet_File_Node	*find_node_by_name(Eet_File *ef, const char *name);
static int		read_data_from_disk(Eet_File *ef, Eet_File_Node *efn, void *buf, int len);

/* cache. i don't expect this to ever be large, so arrays will do */
static int        eet_writers_num     = 0;
static int        eet_writers_alloc   = 0;
static Eet_File **eet_writers         = NULL;
static int        eet_readers_num     = 0;
static int        eet_readers_alloc   = 0;
static Eet_File **eet_readers         = NULL;
static int        eet_initcount       = 0;

/* Check to see its' an eet file pointer */
static inline int
eet_check_pointer(const Eet_File *ef)
{
  if ((!ef) || (ef->magic != EET_MAGIC_FILE))
    return 1;
  return 0;
}

static inline int
eet_check_header(const Eet_File *ef)
{
   if (!ef->header)
     return 1;
   if (!ef->header->directory)
     return 1;
   return 0;
}

static inline int
eet_test_close(int test, Eet_File *ef)
{
   if (test)
     {
	ef->delete_me_now = 1;
	eet_close(ef);
     }
   return test;
}

/* find an eet file in the currently in use cache */
static Eet_File *
eet_cache_find(const char *path, Eet_File **cache, int cache_num)
{
   int i;

   /* walk list */
   for (i = 0; i < cache_num; i++)
     {
	/* if matches real path - return it */
	if (eet_string_match(cache[i]->path, path))
	  {
	     if (!cache[i]->delete_me_now)
	       return cache[i];
	  }
     }

   /* not found */
   return NULL;
}

/* add to end of cache */
static void
eet_cache_add(Eet_File *ef, Eet_File ***cache, int *cache_num, int *cache_alloc)
{
   Eet_File	**new_cache;
   int		new_cache_num;
   int		new_cache_alloc;

   new_cache_num = *cache_num;
   if (new_cache_num >= 64) /* avoid fd overruns - limit to 128 (most recent) in the cache */
     {
	Eet_File	*del_ef = NULL;
	int		i;

	new_cache = *cache;
	for (i = 0; i < new_cache_num; i++)
	  {
	     if (new_cache[i]->references == 0)
	       {
		  del_ef = new_cache[i];
		  break;
	       }
	  }

	if (del_ef)
	  {
	     del_ef->delete_me_now = 1;
	     eet_close(del_ef);
	  }
     }

   new_cache = *cache;
   new_cache_num = *cache_num;
   new_cache_alloc = *cache_alloc;
   new_cache_num++;
   if (new_cache_num > new_cache_alloc)
     {
	new_cache_alloc += 16;
	new_cache = realloc(new_cache, new_cache_alloc * sizeof(Eet_File *));
	if (!new_cache)
	  {
	     fprintf(stderr, "BAD ERROR! Eet realloc of cache list failed. Abort\n");
	     abort();
	  }
     }
   new_cache[new_cache_num - 1] = ef;
   *cache = new_cache;
   *cache_num = new_cache_num;
   *cache_alloc = new_cache_alloc;
}

/* delete from cache */
static void
eet_cache_del(Eet_File *ef, Eet_File ***cache, int *cache_num, int *cache_alloc)
{
   Eet_File **new_cache;
   int new_cache_num, new_cache_alloc;
   int i, j;

   new_cache = *cache;
   new_cache_num = *cache_num;
   new_cache_alloc = *cache_alloc;
   if (new_cache_num <= 0)
     return;

   for (i = 0; i < new_cache_num; i++)
     {
	if (new_cache[i] == ef)
	  break;
     }

   if (i >= new_cache_num)
     return;

   new_cache_num--;
   for (j = i; j < new_cache_num; j++)
     new_cache[j] = new_cache[j + 1];

   if (new_cache_num < (new_cache_alloc - 16))
     {
	new_cache_alloc -= 16;
	if (new_cache_num > 0)
	  {
	     new_cache = realloc(new_cache, new_cache_alloc * sizeof(Eet_File *));
	     if (!new_cache)
	       {
		  fprintf(stderr, "BAD ERROR! Eet realloc of cache list failed. Abort\n");
		  abort();
	       }
	  }
	else
	  {
	     free(new_cache);
	     new_cache = NULL;
	  }
     }
   *cache = new_cache;
   *cache_num = new_cache_num;
   *cache_alloc = new_cache_alloc;
}

/* internal string match. null friendly, catches same ptr */
static int
eet_string_match(const char *s1, const char *s2)
{
   /* both null- no match */
   if ((!s1) || (!s2)) return 0;
   if (s1 == s2) return 1;
   return (!strcmp(s1, s2));
}

/* flush out writes to a v2 eet file */
static Eet_Error
eet_flush2(Eet_File *ef)
{
   Eet_File_Node        *efn;
   Eet_Error             error = EET_ERROR_NONE;
   int                   head[EET_FILE2_HEADER_COUNT];
   int                   num_directory_entries = 0;
   int                   num_dictionary_entries = 0;
   int                   bytes_directory_entries = 0;
   int                   bytes_dictionary_entries = 0;
   int                   bytes_strings = 0;
   int                   data_offset = 0;
   int                   strings_offset = 0;
   int                   num;
   int                   i;
   int                   j;

   if (eet_check_pointer(ef))
     return EET_ERROR_BAD_OBJECT;
   if (eet_check_header(ef))
     return EET_ERROR_EMPTY;
   if ((ef->mode != EET_FILE_MODE_WRITE) && (ef->mode != EET_FILE_MODE_READ_WRITE))
     return EET_ERROR_NOT_WRITABLE;
   if (!ef->writes_pending)
     return EET_ERROR_NONE;

   /* calculate string base offset and data base offset */
   num = (1 << ef->header->directory->size);
   for (i = 0; i < num; ++i)
     {
        for (efn = ef->header->directory->nodes[i]; efn; efn = efn->next)
          {
             num_directory_entries++;
             bytes_strings += strlen(efn->name) + 1;
          }
     }
   if (ef->ed)
     {
        num_dictionary_entries = ef->ed->count;

        for (i = 0; i < num_dictionary_entries; ++i)
          bytes_strings += ef->ed->all[i].len;
     }

   /* calculate section bytes size */
   bytes_directory_entries = EET_FILE2_DIRECTORY_ENTRY_SIZE * num_directory_entries + EET_FILE2_HEADER_SIZE;
   bytes_dictionary_entries = EET_FILE2_DICTIONARY_ENTRY_SIZE * num_dictionary_entries;

   /* calculate per entry offset */
   strings_offset = bytes_directory_entries + bytes_dictionary_entries;
   data_offset = bytes_directory_entries + bytes_dictionary_entries + bytes_strings;

   for (i = 0; i < num; ++i)
     {
        for (efn = ef->header->directory->nodes[i]; efn; efn = efn->next)
          {
             efn->offset = data_offset;
             data_offset += efn->size;

             efn->name_offset = strings_offset;
             strings_offset += efn->name_size;
          }
     }

   /* calculate dictionary strings offset */
   if (ef->ed)
     ef->ed->offset = strings_offset;

   /* go thru and write the header */
   head[0] = (int) htonl ((unsigned int) EET_MAGIC_FILE2);
   head[1] = (int) htonl ((unsigned int) num_directory_entries);
   head[2] = (int) htonl ((unsigned int) num_dictionary_entries);

   fseek(ef->fp, 0, SEEK_SET);
   if (fwrite(head, sizeof (head), 1, ef->fp) != 1)
     goto write_error;

   /* write directories entry */
   j = 0;
   for (i = 0; i < num; i++)
     {
        for (efn = ef->header->directory->nodes[i]; efn; efn = efn->next)
          {
             int        ibuf[EET_FILE2_DIRECTORY_ENTRY_COUNT];

             ibuf[0] = (int) htonl ((unsigned int) efn->offset);
             ibuf[1] = (int) htonl ((unsigned int) efn->size);
             ibuf[2] = (int) htonl ((unsigned int) efn->data_size);
             ibuf[3] = (int) htonl ((unsigned int) efn->name_offset);
             ibuf[4] = (int) htonl ((unsigned int) efn->name_size);
             ibuf[5] = (int) htonl ((unsigned int) efn->compression);

             if (fwrite(ibuf, sizeof(ibuf), 1, ef->fp) != 1)
               goto write_error;
          }
     }

   /* write dictionnary */
   if (ef->ed)
     {
        int     offset = strings_offset;

        for (j = 0; j < ef->ed->count; ++j)
          {
             int      sbuf[EET_FILE2_DICTIONARY_ENTRY_COUNT];

             sbuf[0] = (int) htonl ((unsigned int) ef->ed->all[j].hash);
             sbuf[1] = (int) htonl ((unsigned int) offset);
             sbuf[2] = (int) htonl ((unsigned int) ef->ed->all[j].len);
             sbuf[3] = (int) htonl ((unsigned int) ef->ed->all[j].prev);
             sbuf[4] = (int) htonl ((unsigned int) ef->ed->all[j].next);

             offset += ef->ed->all[j].len;

             if (fwrite(sbuf, sizeof (sbuf), 1, ef->fp) != 1)
               goto write_error;
          }
     }

   /* write directories name */
   for (i = 0; i < num; i++)
     {
        for (efn = ef->header->directory->nodes[i]; efn; efn = efn->next)
          {
             if (fwrite(efn->name, efn->name_size, 1, ef->fp) != 1)
               goto write_error;
          }
     }

   /* write strings */
   if (ef->ed)
     {
	for (j = 0; j < ef->ed->count; ++j)
	  {
	     if (ef->ed->all[j].str)
	       {
		  if (fwrite(ef->ed->all[j].str, ef->ed->all[j].len, 1, ef->fp) != 1)
		    goto write_error;
	       }
	     else
	       {
		  if (fwrite(ef->ed->all[j].mmap, ef->ed->all[j].len, 1, ef->fp) != 1)
		    goto write_error;
	       }
	  }
     }

   /* write data */
   for (i = 0; i < num; i++)
     {
        for (efn = ef->header->directory->nodes[i]; efn; efn = efn->next)
          {
             if (fwrite(efn->data, efn->size, 1, ef->fp) != 1)
               goto write_error;
          }
     }

   /* no more writes pending */
   ef->writes_pending = 0;

   return EET_ERROR_NONE;

   write_error:
   switch (ferror(ef->fp))
     {
      case EFBIG: error = EET_ERROR_WRITE_ERROR_FILE_TOO_BIG; break;
      case EIO: error = EET_ERROR_WRITE_ERROR_IO_ERROR; break;
      case ENOSPC: error = EET_ERROR_WRITE_ERROR_OUT_OF_SPACE; break;
      case EPIPE: error = EET_ERROR_WRITE_ERROR_FILE_CLOSED; break;
      default: error = EET_ERROR_WRITE_ERROR; break;
     }
   fclose(ef->fp);
   ef->fp = NULL;
   return error;
}

#if 0 /* Unused */
/* flush out writes to an eet file */
static Eet_Error
eet_flush(Eet_File *ef)
{
   Eet_File_Node	*efn;
   int			head[3];
   int			count = 0;
   int			size = 0;
   int			offset = 0;
   int			i;
   int			num;

   /* check to see its' an eet file pointer */
   if (eet_check_pointer(ef))
     return EET_ERROR_BAD_OBJECT;
   if (eet_check_header(ef))
     return EET_ERROR_EMPTY;
   if ((ef->mode != EET_FILE_MODE_WRITE) && (ef->mode != EET_FILE_MODE_READ_WRITE))
     return EET_ERROR_NOT_WRITABLE;
   if (!ef->writes_pending)
     return EET_ERROR_NONE;

   /* calculate total size in bytes of directory block */
   num = (1 << ef->header->directory->size);
   for (i = 0; i < num; i++)
     {
	for (efn = ef->header->directory->nodes[i]; efn; efn = efn->next)
	  {
	     size += 20 + strlen(efn->name) + 1;
	     count++;
	  }
     }

   /* calculate offsets per entry */
   offset = 0;
   for (i = 0; i < num; i++)
     {
	for (efn = ef->header->directory->nodes[i]; efn; efn = efn->next)
	  {
	     efn->offset = 12 + size + offset;
	     offset += efn->size;
	  }
     }

   /* go thru and write the header */
   head[0] = (int) htonl ((unsigned int) EET_MAGIC_FILE);
   head[1] = (int) htonl ((unsigned int) count);
   head[2] = (int) htonl ((unsigned int) size);

   fseek(ef->fp, 0, SEEK_SET);
   if (fwrite(head, 12, 1, ef->fp) != 1)
     goto write_error;

   for (i = 0; i < num; i++)
     {
	for (efn = ef->header->directory->nodes[i]; efn; efn = efn->next)
	  {
	     unsigned int	ibuf[5];
	     int		name_size;

	     name_size = strlen(efn->name) + 1;

	     ibuf[0] = (int) htonl ((unsigned int) efn->offset);
	     ibuf[1] = (int) htonl ((unsigned int) efn->compression);
	     ibuf[2] = (int) htonl ((unsigned int) efn->size);
	     ibuf[3] = (int) htonl ((unsigned int) efn->data_size);
	     ibuf[4] = (int) htonl ((unsigned int) name_size);


	     if (fwrite(ibuf, sizeof(ibuf), 1, ef->fp) != 1)
	       goto write_error;
	     if (fwrite(efn->name, name_size, 1, ef->fp) != 1)
	       goto write_error;
	  }
     }

   /* write data */
   for (i = 0; i < num; i++)
     {
	for (efn = ef->header->directory->nodes[i]; efn; efn = efn->next)
	  {
	     if (fwrite(efn->data, efn->size, 1, ef->fp) != 1)
	       goto write_error;
	  }
     }

   /* no more writes pending */
   ef->writes_pending = 0;

   return EET_ERROR_NONE;

   write_error:
   switch (ferror(ef->fp))
     {
      case EFBIG:
	fclose(ef->fp);
	ef->fp = NULL;
	return EET_ERROR_WRITE_ERROR_FILE_TOO_BIG;
      case EIO:
	fclose(ef->fp);
	ef->fp = NULL;
	return EET_ERROR_WRITE_ERROR_IO_ERROR;
      case ENOSPC:
	fclose(ef->fp);
	ef->fp = NULL;
	return EET_ERROR_WRITE_ERROR_OUT_OF_SPACE;
      case EPIPE:
	fclose(ef->fp);
	ef->fp = NULL;
	return EET_ERROR_WRITE_ERROR_FILE_CLOSED;
      default:
	fclose(ef->fp);
	ef->fp = NULL;
	return EET_ERROR_WRITE_ERROR;
     }
   fclose(ef->fp);
   ef->fp = NULL;
   return EET_ERROR_WRITE_ERROR;
}
#endif

EAPI int
eet_init(void)
{
   return ++eet_initcount;
}

EAPI int
eet_shutdown(void)
{
   if (--eet_initcount == 0)
     {
	eet_clearcache();
	_eet_memfile_shutdown();
     }

   return eet_initcount;
}

EAPI void
eet_clearcache(void)
{
   int	num = 0;
   int	i;

   /*
    * We need to compute the list of eet file to close separately from the cache,
    * due to eet_close removing them from the cache after each call.
    */
   for (i = 0; i < eet_writers_num; i++)
     {
	if (eet_writers[i]->references <= 0) num++;
     }

   for (i = 0; i < eet_readers_num; i++)
     {
	if (eet_readers[i]->references <= 0) num++;
     }

   if (num > 0)
     {
	Eet_File **closelist = NULL;

	closelist = alloca(num * sizeof(Eet_File *));
	num = 0;
	for (i = 0; i < eet_writers_num; i++)
	  {
	     if (eet_writers[i]->references <= 0)
	       {
		  closelist[num] = eet_writers[i];
		  eet_writers[i]->delete_me_now = 1;
		  num++;
	       }
	  }

	for (i = 0; i < eet_readers_num; i++)
	  {
	     if (eet_readers[i]->references <= 0)
	       {
		  closelist[num] = eet_readers[i];
		  eet_readers[i]->delete_me_now = 1;
		  num++;
	       }
	  }

	for (i = 0; i < num; i++)
	  {
	     eet_close(closelist[i]);
	  }
     }
}

/* FIXME: MMAP race condition in READ_WRITE_MODE */
static Eet_File *
eet_internal_read2(Eet_File *ef)
{
   const int    *data = (const int*) ef->data;
   const char   *start = (const char*) ef->data;
   int           index = 0;
   int           num_directory_entries;
   int           bytes_directory_entries;
   int           num_dictionary_entries;
   int           bytes_dictionary_entries;
   int           i;

   index += sizeof(int);
   if (eet_test_close((int) ntohl(*data) != EET_MAGIC_FILE2, ef))
     return NULL;
   data++;

#define GET_INT(Value, Pointer, Index)          \
   {                                            \
      Value = ntohl(*Pointer);                  \
      Pointer++;                                \
      Index += sizeof(int);                     \
   }

   /* get entries count and byte count */
   GET_INT(num_directory_entries, data, index);
   /* get dictionary count and byte count */
   GET_INT(num_dictionary_entries, data, index);

   bytes_directory_entries = EET_FILE2_DIRECTORY_ENTRY_SIZE * num_directory_entries + EET_FILE2_HEADER_SIZE;
   bytes_dictionary_entries = EET_FILE2_DICTIONARY_ENTRY_SIZE * num_dictionary_entries;

   /* we cant have <= 0 values here - invalid */
   if (eet_test_close((num_directory_entries <= 0), ef))
     return NULL;

   /* we cant have more bytes directory and bytes in dictionaries than the size of the file */
   if (eet_test_close((bytes_directory_entries + bytes_dictionary_entries) > ef->data_size, ef))
     return NULL;

   /* allocate header */
   ef->header = calloc(1, sizeof(Eet_File_Header));
   if (eet_test_close(!ef->header, ef))
     return NULL;

   ef->header->magic = EET_MAGIC_FILE_HEADER;

   /* allocate directory block in ram */
   ef->header->directory = calloc(1, sizeof(Eet_File_Directory));
   if (eet_test_close(!ef->header->directory, ef))
     return NULL;

   /* 8 bit hash table (256 buckets) */
   ef->header->directory->size = 8;
   /* allocate base hash table */
   ef->header->directory->nodes = calloc(1, sizeof(Eet_File_Node *) * (1 << ef->header->directory->size));
   if (eet_test_close(!ef->header->directory->nodes, ef))
     return NULL;

   /* actually read the directory block - all of it, into ram */
   for (i = 0; i < num_directory_entries; ++i)
     {
        const char      *name;
        Eet_File_Node   *efn;
        int              name_offset;
        int              name_size;
        int              hash;

        /* out directory block is inconsistent - we have oveerun our */
        /* dynamic block buffer before we finished scanning dir entries */
        efn = malloc (sizeof(Eet_File_Node));
        if (eet_test_close(!efn, ef))
          return NULL;

        /* get entrie header */
        GET_INT(efn->offset, data, index);
        GET_INT(efn->size, data, index);
        GET_INT(efn->data_size, data, index);
        GET_INT(name_offset, data, index);
        GET_INT(name_size, data, index);
        GET_INT(efn->compression, data, index);

#define EFN_TEST(Test, Ef, Efn)                 \
        if (eet_test_close(Test, Ef))           \
          {                                     \
             free(Efn);                         \
             return NULL;                       \
          }

        /* check data pointer position */
        EFN_TEST(!((efn->size > 0)
                   && (efn->offset + efn->size <= ef->data_size)
                   && (efn->offset > bytes_dictionary_entries + bytes_directory_entries)), ef, efn);

        /* check name position */
        EFN_TEST(!((name_size > 0)
                   && (name_offset + name_size < ef->data_size)
                   && (name_offset >= bytes_dictionary_entries + bytes_directory_entries)), ef, efn);

        name = start + name_offset;

        /* check '\0' at the end of name string */
        EFN_TEST(name[name_size - 1] != '\0', ef, efn);

        efn->free_name = 0;
        efn->name = (char*) name;
        efn->name_size = name_size;

        hash = _eet_hash_gen(efn->name, ef->header->directory->size);
        efn->next = ef->header->directory->nodes[hash];
        ef->header->directory->nodes[hash] = efn;

        /* read-only mode, so currently we have no data loaded */
        if (ef->mode == EET_FILE_MODE_READ)
          efn->data = NULL;
        /* read-write mode - read everything into ram */
        else
          {
             efn->data = malloc(efn->size);
             if (efn->data)
               memcpy(efn->data, ef->data + efn->offset, efn->size);
          }
     }

   ef->ed = NULL;

   if (num_dictionary_entries)
     {
        const int       *dico = (const int*) ef->data + EET_FILE2_DIRECTORY_ENTRY_COUNT * num_directory_entries + EET_FILE2_HEADER_COUNT;
        int              j;

        if (eet_test_close((num_directory_entries * EET_FILE2_DICTIONARY_ENTRY_SIZE + index) > (bytes_dictionary_entries + bytes_directory_entries), ef))
            return NULL;

        ef->ed = calloc(1, sizeof (Eet_Dictionary));
        if (eet_test_close(!ef->ed, ef)) return NULL;

        ef->ed->all = calloc(num_dictionary_entries, sizeof (Eet_String));
        if (eet_test_close(!ef->ed->all, ef)) return NULL;

        ef->ed->count = num_dictionary_entries;
	ef->ed->total = num_dictionary_entries;
	ef->ed->start = start + bytes_dictionary_entries + bytes_directory_entries;
	ef->ed->end = ef->ed->start;

        for (j = 0; j < ef->ed->count; ++j)
          {
             int   hash;
             int   offset;

             GET_INT(hash, dico, index);
             GET_INT(offset, dico, index);
             GET_INT(ef->ed->all[j].len, dico, index);
             GET_INT(ef->ed->all[j].prev, dico, index);
             GET_INT(ef->ed->all[j].next, dico, index);

             /* Hash value could be stored on 8bits data, but this will break alignment of all the others data.
                So stick to int and check the value. */
             if (eet_test_close(hash & 0xFFFFFF00, ef)) return NULL;

             /* Check string position */
             if (eet_test_close(!((ef->ed->all[j].len > 0)
                                  && (offset > (bytes_dictionary_entries + bytes_directory_entries))
                                  && (offset + ef->ed->all[j].len < ef->data_size)), ef))
               return NULL;

             ef->ed->all[j].mmap = start + offset;
             ef->ed->all[j].str = NULL;

	     if (ef->ed->all[j].mmap + ef->ed->all[j].len > ef->ed->end)
	       ef->ed->end = ef->ed->all[j].mmap + ef->ed->all[j].len;

             /* Check '\0' at the end of the string */
             if (eet_test_close(ef->ed->all[j].mmap[ef->ed->all[j].len - 1] != '\0', ef)) return NULL;

             if (ef->ed->all[j].prev == -1)
               ef->ed->hash[hash] = j;
          }
     }

   return ef;
}

#if EET_OLD_EET_FILE_FORMAT
static Eet_File *
eet_internal_read1(Eet_File *ef)
{
   const unsigned char	*dyn_buf = NULL;
   const unsigned char	*p = NULL;
   int			 index = 0;
   int			 num_entries;
   int			 byte_entries;
   int			 i;

   fprintf(stderr, "EET file format of '%s' is deprecated. You should just open it one time with mode == EET_FILE_MODE_READ_WRITE to solve this issue.\n", ef->path);

   /* build header table if read mode */
   /* geat header */
   index += sizeof(int);
   if (eet_test_close((int)ntohl(*((int *)ef->data)) != EET_MAGIC_FILE, ef))
     return NULL;

#define EXTRACT_INT(Value, Pointer, Index) \
        { \
	   int tmp; \
	   memcpy(&tmp, Pointer + Index, sizeof(int)); \
	   Value = ntohl(tmp); \
	   Index += sizeof(int); \
        }

   /* get entries count and byte count */
   EXTRACT_INT(num_entries, ef->data, index);
   EXTRACT_INT(byte_entries, ef->data, index);

   /* we cant have <= 0 values here - invalid */
   if (eet_test_close((num_entries <= 0) || (byte_entries <= 0), ef))
     return NULL;

   /* we can't have more entires than minimum bytes for those! invalid! */
   if (eet_test_close((num_entries * 20) > byte_entries, ef))
     return NULL;

   /* check we will not outrun the file limit */
   if (eet_test_close(((byte_entries + sizeof(int) * 3) > ef->data_size), ef))
     return NULL;

   /* allocate header */
   ef->header = calloc(1, sizeof(Eet_File_Header));
   if (eet_test_close(!ef->header, ef))
     return NULL;

   ef->header->magic = EET_MAGIC_FILE_HEADER;

   /* allocate directory block in ram */
   ef->header->directory = calloc(1, sizeof(Eet_File_Directory));
   if (eet_test_close(!ef->header->directory, ef))
     return NULL;

   /* 8 bit hash table (256 buckets) */
   ef->header->directory->size = 8;
   /* allocate base hash table */
   ef->header->directory->nodes = calloc(1, sizeof(Eet_File_Node *) * (1 << ef->header->directory->size));
   if (eet_test_close(!ef->header->directory->nodes, ef))
     return NULL;

   /* actually read the directory block - all of it, into ram */
   dyn_buf = ef->data + index;

   /* parse directory block */
   p = dyn_buf;

   for (i = 0; i < num_entries; i++)
     {
	Eet_File_Node	*efn;
	void		*data = NULL;
	int		indexn = 0;
	int		name_size;
	int		hash;
	int		k;

#define HEADER_SIZE (sizeof(int) * 5)

	/* out directory block is inconsistent - we have oveerun our */
	/* dynamic block buffer before we finished scanning dir entries */
	if (eet_test_close(p + HEADER_SIZE >= (dyn_buf + byte_entries), ef))
	  return NULL;

	/* allocate all the ram needed for this stored node accounting */
	efn = malloc (sizeof(Eet_File_Node));
	if (eet_test_close(!efn, ef))
	  return NULL;

        /* get entrie header */
	EXTRACT_INT(efn->offset, p, indexn);
	EXTRACT_INT(efn->compression, p, indexn);
	EXTRACT_INT(efn->size, p, indexn);
	EXTRACT_INT(efn->data_size, p, indexn);
	EXTRACT_INT(name_size, p, indexn);

        efn->name_size = name_size;

	/* invalid size */
	if (eet_test_close(efn->size <= 0, ef))
	  {
	     free (efn);
	     return NULL;
	  }

	/* invalid name_size */
	if (eet_test_close(name_size <= 0, ef))
	  {
	     free (efn);
	     return NULL;
	  }

	/* reading name would mean falling off end of dyn_buf - invalid */
	if (eet_test_close((p + 16 + name_size) > (dyn_buf + byte_entries), ef))
	  {
	     free (efn);
	     return NULL;
	  }

	/* This code is useless if we dont want backward compatibility */
	for (k = name_size; k > 0 && ((unsigned char) * (p + HEADER_SIZE + k)) != 0; --k)
	  ;

	efn->free_name = ((unsigned char) * (p + HEADER_SIZE + k)) != 0;

	if (efn->free_name)
	  {
	     efn->name = malloc(sizeof(char) * name_size + 1);
	     if (eet_test_close(efn->name == NULL, ef))
	       {
		  free (efn);
		  return NULL;
	       }

	     strncpy(efn->name, (char *)p + HEADER_SIZE, name_size);
	     efn->name[name_size] = 0;

	     printf("File: %s is not up to date for key \"%s\" - needs rebuilding sometime\n", ef->path, efn->name);
	  }
	else
	  /* The only really usefull peace of code for efn->name (no backward compatibility) */
	  efn->name = (char*)((unsigned char*)(p + HEADER_SIZE));

	/* get hash bucket it should go in */
	hash = _eet_hash_gen(efn->name, ef->header->directory->size);
	efn->next = ef->header->directory->nodes[hash];
	ef->header->directory->nodes[hash] = efn;

	/* read-only mode, so currently we have no data loaded */
	if (ef->mode == EET_FILE_MODE_READ)
	  efn->data = NULL;
	/* read-write mode - read everything into ram */
	else
	  {
	     data = malloc(efn->size);
	     if (data)
	       memcpy(data, ef->data + efn->offset, efn->size);
	     efn->data = data;
	  }
	/* advance */
	p += HEADER_SIZE + name_size;
     }
   return ef;
}
#endif

#if EET_OLD_EET_FILE_FORMAT
static Eet_File *
eet_internal_read(Eet_File *ef)
{
   const int    *data = (const int*) ef->data;

   if (eet_test_close((ef->data == (void *)-1) || (ef->data == NULL), ef))
     return NULL;

   if (eet_test_close(ef->data_size < sizeof(int) * 3, ef))
     return NULL;

   switch (ntohl(*data))
     {
#if EET_OLD_EET_FILE_FORMAT
      case EET_MAGIC_FILE:
	return eet_internal_read1(ef);
#endif
      case EET_MAGIC_FILE2:
	return eet_internal_read2(ef);
      default:
	ef->delete_me_now = 1;
	eet_close(ef);
	break;
     }

   return NULL;
}

#if 0 /* No prototype */
EAPI Eet_File *
eet_memopen_read(const void *data, size_t size)
{
   Eet_File	*ef;

   if (data == NULL || size == 0)
     return NULL;

   ef = malloc (sizeof (Eet_File));
   if (!ef)
     return NULL;

   ef->ed = NULL;
   ef->path = NULL;
   ef->magic = EET_MAGIC_FILE;
   ef->references = 1;
   ef->mode = EET_FILE_MODE_READ;
   ef->header = NULL;
   ef->mtime = 0;
   ef->delete_me_now = 1;
   ef->fp = NULL;
   ef->data = data;
   ef->data_size = size;

   return eet_internal_read(ef);
}
#endif

EAPI Eet_File *
eet_open(const char *file, Eet_File_Mode mode)
{
   FILE         *fp;
   Eet_File	*ef;
   int		 file_len;
   struct stat	 file_stat;

   if (!file)
     return NULL;

   /* find the current file handle in cache*/
   ef = NULL;
   if (mode == EET_FILE_MODE_READ)
     {
	ef = eet_cache_find((char *)file, eet_writers, eet_writers_num);
	if (ef)
	  {
	     eet_flush2(ef);
	     ef->references++;
	     ef->delete_me_now = 1;
	     eet_close(ef);
	  }
	ef = eet_cache_find((char *)file, eet_readers, eet_readers_num);
     }
   else if ((mode == EET_FILE_MODE_WRITE) ||
	    (mode == EET_FILE_MODE_READ_WRITE))
     {
	ef = eet_cache_find((char *)file, eet_readers, eet_readers_num);
	if (ef)
	  {
	     ef->delete_me_now = 1;
	     ef->references++;
	     eet_close(ef);
	  }
	ef = eet_cache_find((char *)file, eet_writers, eet_writers_num);
     }

    /* try open the file based on mode */
   if ((mode == EET_FILE_MODE_READ) || (mode == EET_FILE_MODE_READ_WRITE))
     {
	fp = fopen(file, "rb");
	if (!fp) goto on_error;
	if (fstat(fileno(fp), &file_stat))
	  {
	     fclose(fp);
	     fp = NULL;
	     goto on_error;
	  }
	if ((mode == EET_FILE_MODE_READ) &&
	    (file_stat.st_size < (sizeof(int) * 3)))
	  {
	     fclose(fp);
	     fp = NULL;
	     goto on_error;
	  }

     on_error:
	if (fp == NULL && mode == EET_FILE_MODE_READ) return NULL;
     }
   else
     {
	if (mode != EET_FILE_MODE_WRITE) return NULL;
	memset(&file_stat, 0, sizeof(file_stat));
	/* opening for write - delete old copy of file right away */
	unlink(file);
	fp = fopen(file, "wb");
     }

   /* We found one */
   if (ef && (file_stat.st_mtime != ef->mtime))
     {
	ef->delete_me_now = 1;
	ef->references++;
	eet_close(ef);
	ef = NULL;
     }

   if (ef)
     {
	/* reference it up and return it */
	if (fp != NULL) fclose(fp);
	ef->references++;
	return ef;
     }

   file_len = strlen(file) + 1;

   /* Allocate struct for eet file and have it zero'd out */
   ef = malloc(sizeof(Eet_File) + file_len);
   if (!ef)
     return NULL;

   /* fill some of the members */
   ef->fp = fp;
   ef->readfp = NULL;
   ef->path = ((char *)ef) + sizeof(Eet_File);
   memcpy(ef->path, file, file_len);
   ef->magic = EET_MAGIC_FILE;
   ef->references = 1;
   ef->mode = mode;
   ef->header = NULL;
   ef->mtime = file_stat.st_mtime;
   ef->delete_me_now = 0;
   ef->data = NULL;
   ef->data_size = 0;

   ef->ed = (mode == EET_FILE_MODE_WRITE)
     || (ef->fp == NULL && mode == EET_FILE_MODE_READ_WRITE) ?
     eet_dictionary_add() : NULL;

   if (ef->fp == NULL && mode == EET_FILE_MODE_READ_WRITE) goto empty_file;

   /* if we can't open - bail out */
   if (eet_test_close(!ef->fp, ef))
     return NULL;

   fcntl(fileno(ef->fp), F_SETFD, FD_CLOEXEC);
   /* if we opened for read or read-write */
   if ((mode == EET_FILE_MODE_READ) || (mode == EET_FILE_MODE_READ_WRITE))
     {
	ef->data_size = file_stat.st_size;
	ef->data = mmap(NULL, ef->data_size, PROT_READ,
			MAP_SHARED, fileno(ef->fp), 0);

	ef = eet_internal_read(ef);
	if (!ef)
	  return NULL;
     }

 empty_file:
   /* we need to delete the original file in read-write mode and re-open for writing */
   if (ef->mode == EET_FILE_MODE_READ_WRITE)
     {
	ef->readfp = ef->fp;
	unlink(ef->path);
	ef->fp = fopen(ef->path, "wb");
	fcntl(fileno(ef->fp), F_SETFD, FD_CLOEXEC);
     }

   /* add to cache */
   if (ef->references == 1)
     {
	if (ef->mode == EET_FILE_MODE_READ)
	  eet_cache_add(ef, &eet_readers, &eet_readers_num, &eet_readers_alloc);
	else
	  if ((ef->mode == EET_FILE_MODE_WRITE) || (ef->mode == EET_FILE_MODE_READ_WRITE))
	    eet_cache_add(ef, &eet_writers, &eet_writers_num, &eet_writers_alloc);
     }

   return ef;
}
#endif

EAPI Eet_File_Mode
eet_mode_get(Eet_File *ef)
{
   /* check to see its' an eet file pointer */
   if ((!ef) || (ef->magic != EET_MAGIC_FILE))
     return EET_FILE_MODE_INVALID;
   else
     return ef->mode;
}

EAPI Eet_Error
eet_close(Eet_File *ef)
{
   Eet_Error err;

   /* check to see its' an eet file pointer */
   if (eet_check_pointer(ef))
     return EET_ERROR_BAD_OBJECT;
   /* deref */
   ef->references--;
   /* if its still referenced - dont go any further */
   if (ef->references > 0) return EET_ERROR_NONE;
   /* flush any writes */
   err = eet_flush2(ef);

   /* if not urgent to delete it - dont free it - leave it in cache */
   if ((!ef->delete_me_now) && (ef->mode == EET_FILE_MODE_READ))
     return EET_ERROR_NONE;

   /* remove from cache */
   if (ef->mode == EET_FILE_MODE_READ)
     eet_cache_del(ef, &eet_readers, &eet_readers_num, &eet_readers_alloc);
   else if ((ef->mode == EET_FILE_MODE_WRITE) || (ef->mode == EET_FILE_MODE_READ_WRITE))
     eet_cache_del(ef, &eet_writers, &eet_writers_num, &eet_writers_alloc);

   /* free up data */
   if (ef->header)
     {
	if (ef->header->directory)
	  {
	     if (ef->header->directory->nodes)
	       {
		  int i, num;

		  num = (1 << ef->header->directory->size);
		  for (i = 0; i < num; i++)
		    {
		       Eet_File_Node *efn;

		       while ((efn = ef->header->directory->nodes[i]))
			 {
			    if (efn->data)
			      free(efn->data);

			    ef->header->directory->nodes[i] = efn->next;

			    if (efn->free_name)
			      free(efn->name);

			    free(efn);
			 }
		    }
		  free(ef->header->directory->nodes);
	       }
	     free(ef->header->directory);
	  }
	free(ef->header);
     }

   eet_dictionary_free(ef->ed);

   if (ef->data) munmap((void*)ef->data, ef->data_size);
   if (ef->fp) fclose(ef->fp);
   if (ef->readfp) fclose(ef->readfp);

   /* zero out ram for struct - caution tactic against stale memory use */
   memset(ef, 0, sizeof(Eet_File));

   /* free it */
   free(ef);
   return err;
}

EAPI void *
eet_read(Eet_File *ef, const char *name, int *size_ret)
{
   void			*data = NULL;
   int			size = 0;
   Eet_File_Node	*efn;

   if (size_ret)
     *size_ret = 0;

   /* check to see its' an eet file pointer */
   if (eet_check_pointer(ef))
     return NULL;
   if (!name)
     return NULL;
   if ((ef->mode != EET_FILE_MODE_READ) &&
       (ef->mode != EET_FILE_MODE_READ_WRITE))
     return NULL;

   /* no header, return NULL */
   if (eet_check_header(ef))
     return NULL;

   /* hunt hash bucket */
   efn = find_node_by_name(ef, name);
   if (!efn)
     return NULL;

   /* get size (uncompressed, if compressed at all) */
   size = efn->data_size;

   /* allocate data */
   data = malloc(size);
   if (!data)
     return NULL;

   /* uncompressed data */
   if (efn->compression == 0)
     {
	/* if we alreayd have the data in ram... copy that */
	if (efn->data)
	  memcpy(data, efn->data, efn->size);
	else
	  if (!read_data_from_disk(ef, efn, data, size))
	    {
	       free(data);
	       return NULL;
	    }
     }
   /* compressed data */
   else
     {
	void	*tmp_data;
	int	free_tmp = 0;
	int	compr_size = efn->size;
	uLongf	dlen;

	/* if we already have the data in ram... copy that */
	if (efn->data)
	  tmp_data = efn->data;
	else
	  {
	     tmp_data = malloc(compr_size);
	     if (!tmp_data)
	       {
		  free(data);
		  return NULL;
	       }

	     free_tmp = 1;

	     if (!read_data_from_disk(ef, efn, tmp_data, compr_size))
	       {
		  free(tmp_data);
		  free(data);
		  return NULL;
	       }
	  }

	/* decompress it */
	dlen = size;
	if (uncompress((Bytef *)data, &dlen,
		 tmp_data, (uLongf)compr_size))
	  {
	     free(data);
	     return NULL;
	  }

	if (free_tmp)
	  free(tmp_data);
     }

   /* fill in return values */
   if (size_ret)
     *size_ret = size;

   return data;
}

EAPI const void *
eet_read_direct(Eet_File *ef, const char *name, int *size_ret)
{
   const void	*data = NULL;
   int		 size = 0;
   Eet_File_Node *efn;

   if (size_ret)
     *size_ret = 0;

   /* check to see its' an eet file pointer */
   if (eet_check_pointer(ef))
     return NULL;
   if (!name)
     return NULL;
   if ((ef->mode != EET_FILE_MODE_READ) &&
       (ef->mode != EET_FILE_MODE_READ_WRITE))
     return NULL;

   /* no header, return NULL */
   if (eet_check_header(ef))
     return NULL;

   /* hunt hash bucket */
   efn = find_node_by_name(ef, name);
   if (!efn)
     return NULL;

   if (efn->offset < 0 && efn->data == NULL)
     return NULL;

   /* get size (uncompressed, if compressed at all) */
   size = efn->data_size;

   /* uncompressed data */
   if (efn->compression == 0)
     data = efn->data ? efn->data : ef->data + efn->offset;
   /* compressed data */
   else
     data = NULL;

   /* fill in return values */
   if (size_ret)
     *size_ret = size;

   return data;
}

EAPI int
eet_write(Eet_File *ef, const char *name, const void *data, int size, int compress)
{
   Eet_File_Node	*efn;
   void			*data2;
   int			exists_already = 0;
   int			data_size;
   int			hash;

   /* check to see its' an eet file pointer */
   if (eet_check_pointer(ef))
     return 0;
   if ((!name) || (!data) || (size <= 0))
     return 0;
   if ((ef->mode != EET_FILE_MODE_WRITE) &&
       (ef->mode != EET_FILE_MODE_READ_WRITE))
     return 0;

   if (!ef->header)
     {
	/* allocate header */
	ef->header = calloc(1, sizeof(Eet_File_Header));
	if (!ef->header)
	  return 0;

	ef->header->magic = EET_MAGIC_FILE_HEADER;
	/* allocate directory block in ram */
	ef->header->directory = calloc(1, sizeof(Eet_File_Directory));
	if (!ef->header->directory)
	  return 0;

	/* 8 bit hash table (256 buckets) */
	ef->header->directory->size = 8;
	/* allocate base hash table */
	ef->header->directory->nodes = calloc(1, sizeof(Eet_File_Node *) * (1 << ef->header->directory->size));
	if (!ef->header->directory->nodes)
	  return 0;
     }

   /* figure hash bucket */
   hash = _eet_hash_gen(name, ef->header->directory->size);

   data_size = compress ? 12 + ((size * 101) / 100) : size;

   data2 = malloc(data_size);
   if (!data2)
     return 0;

   /* if we want to compress */
   if (compress)
     {
	uLongf buflen;

	/* compress the data with max compression */
	buflen = (uLongf)data_size;
	if (compress2((Bytef *)data2, &buflen, (Bytef *)data,
			   (uLong)size, Z_BEST_COMPRESSION) != Z_OK)
	  {
	     free(data2);
	     return 0;
	  }
	/* record compressed chunk size */
	data_size = (int)buflen;
	if (data_size < 0 || data_size >= size)
	  {
	     compress = 0;
	     data_size = size;
	  }
	else
	  {
	     void *data3;

	     data3 = realloc(data2, data_size);
	     if (data3)
	       data2 = data3;
	  }
     }
   if (!compress)
     memcpy(data2, data, size);

   /* Does this node already exist? */
   for (efn = ef->header->directory->nodes[hash]; efn; efn = efn->next)
     {
	/* if it matches */
	if ((efn->name) && (eet_string_match(efn->name, name)))
	  {
	     free(efn->data);
	     efn->compression = !!compress;
	     efn->size = data_size;
	     efn->data_size = size;
	     efn->data = data2;
	     efn->offset = -1;
	     exists_already = 1;
	     break;
	  }
     }
   if (!exists_already)
     {
	efn = malloc(sizeof(Eet_File_Node));
	if (!efn)
	  {
	     free(data2);
	     return 0;
	  }
	efn->name = strdup(name);
        efn->name_size = strlen(efn->name) + 1;
        efn->free_name = 1;

	efn->next = ef->header->directory->nodes[hash];
	ef->header->directory->nodes[hash] = efn;
	efn->offset = -1;
	efn->compression = !!compress;
	efn->size = data_size;
	efn->data_size = size;
	efn->data = data2;
     }

   /* flags that writes are pending */
   ef->writes_pending = 1;
   return data_size;
}

EAPI int
eet_delete(Eet_File *ef, const char *name)
{
   Eet_File_Node	*efn;
   Eet_File_Node	*pefn;
   int			hash;
   int			exists_already = 0;

   /* check to see its' an eet file pointer */
   if (eet_check_pointer(ef))
     return 0;
   if (!name)
     return 0;

   /* deleting keys is only possible in RW or WRITE mode */
   if (ef->mode == EET_FILE_MODE_READ)
     return 0;

   if (eet_check_header(ef))
     return 0;

   /* figure hash bucket */
   hash = _eet_hash_gen(name, ef->header->directory->size);

   /* Does this node already exist? */
   for (pefn = NULL, efn = ef->header->directory->nodes[hash];
	efn;
	pefn = efn, efn = efn->next)
     {
	/* if it matches */
	if (eet_string_match(efn->name, name))
	  {
	     if (efn->data)
	       free(efn->data);

	     if (efn == ef->header->directory->nodes[hash])
	       ef->header->directory->nodes[hash] = efn->next;
	     else
	       pefn->next = efn->next;

             if (efn->free_name) free(efn->name);
	     free(efn);
	     exists_already = 1;
	     break;
	  }
     }
   /* flags that writes are pending */
   if (exists_already)
     ef->writes_pending = 1;

   /* update access time */
   return exists_already;
}

EAPI Eet_Dictionary *
eet_dictionary_get(Eet_File *ef)
{
   if (eet_check_pointer(ef)) return NULL;

   return ef->ed;
}


EAPI char **
eet_list(Eet_File *ef, const char *glob, int *count_ret)
{
   Eet_File_Node	*efn;
   char			**list_ret = NULL;
   int			list_count = 0;
   int			list_count_alloc = 0;
   int			i, num;

   /* check to see its' an eet file pointer */
   if (eet_check_pointer(ef) || eet_check_header(ef) ||
       (!glob) ||
       ((ef->mode != EET_FILE_MODE_READ) &&
        (ef->mode != EET_FILE_MODE_READ_WRITE)))
     {
	if (count_ret)
	  *count_ret = 0;

	return NULL;
     }

   /* loop through all entries */
   num = (1 << ef->header->directory->size);
   for (i = 0; i < num; i++)
     {
	for (efn = ef->header->directory->nodes[i]; efn; efn = efn->next)
	  {
	     /* if the entry matches the input glob
	      * check for * explicitly, because on some systems, * isn't well
	      * supported
	      */
	     if ((!strcmp (glob, "*")) || !fnmatch(glob, efn->name, 0))
	       {
		  /* add it to our list */
		  list_count++;

		  /* only realloc in 32 entry chunks */
		  if (list_count > list_count_alloc)
		    {
		       char	**new_list = NULL;

		       list_count_alloc += 64;
		       new_list = realloc(list_ret, list_count_alloc * (sizeof(char *)));
		       if (!new_list)
			 {
			    free(list_ret);

			    if (count_ret)
			      *count_ret = 0;

			    return NULL;
			 }
		       list_ret = new_list;
		    }

		  /* put pointer of name string in */
		  list_ret[list_count - 1] = efn->name;
	       }
	  }
     }

   /* return count and list */
   if (count_ret)
     *count_ret = list_count;

   return list_ret;
}

EAPI int
eet_num_entries(Eet_File *ef)
{
   int i, num, ret = 0;
   Eet_File_Node *efn;

   /* check to see its' an eet file pointer */
   if (eet_check_pointer(ef) || eet_check_header(ef) ||
       ((ef->mode != EET_FILE_MODE_READ) &&
        (ef->mode != EET_FILE_MODE_READ_WRITE)))
     return -1;

   /* loop through all entries */
   num = (1 << ef->header->directory->size);
   for (i = 0; i < num; i++)
     {
	for (efn = ef->header->directory->nodes[i]; efn; efn = efn->next)
	  ret++;
     }

   return ret;
}

static Eet_File_Node *
find_node_by_name(Eet_File *ef, const char *name)
{
   Eet_File_Node *efn;
   int hash;

   /* get hash bucket this should be in */
   hash = _eet_hash_gen(name, ef->header->directory->size);

   for (efn = ef->header->directory->nodes[hash]; efn; efn = efn->next)
     {
	if (eet_string_match(efn->name, name))
	  return efn;
     }

   return NULL;
}

static int
read_data_from_disk(Eet_File *ef, Eet_File_Node *efn, void *buf, int len)
{
   if (efn->offset < 0) return 0;

   if (ef->data)
     {
	if ((efn->offset + len) > ef->data_size) return 0;
	memcpy(buf, ef->data + efn->offset, len);
     }
   else
     {
	/* seek to data location */
	if (fseek(ef->fp, efn->offset, SEEK_SET) < 0)
	  return 0;

	/* read it */
	len = fread(buf, len, 1, ef->fp);
     }
   return len;
}