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

/**
 * @mainpage libinotifytools
 *
 * libinotifytools is a small C library to simplify the use of Linux's inotify
 * interface.
 *
 * @link inotifytools/inotifytools.h Documentation for the library's public
 * interface.@endlink
 *
 * @link todo.html TODO list.@endlink
 */

#include "../../config.h"
#include "inotifytools/inotifytools.h"
#include "inotifytools_p.h"

#include <string.h>
#include <strings.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <errno.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <dirent.h>
#include <time.h>
#include <regex.h>
#include <setjmp.h>

#include "inotifytools/inotify.h"

/**
 * @file inotifytools/inotifytools.h
 * @brief inotifytools library public interface.
 * @author Rohan McGovern, \<rohan@mcgovern.id.au\>
 *
 * This library provides a thin layer on top of the basic inotify interface.
 * The primary use is to easily set up watches on files, potentially many files
 * at once, and read events without having to deal with low-level I/O.  There
 * are also several utility functions for inotify-related string formatting.
 *
 * To use this library, you must \c \#include the following headers accordingly:
 * \li \c \<inotifytools/inotifytools.h\> - to use any functions declared in
 *     this file.
 * \li \c \<inotifytools/inotify.h\> - to have the \c inotify_event type defined
 *     and the numeric IN_* event constants defined.   If \c \<sys/inotify.h\>
 *     was present on your system at compile time, this header simply includes
 *     that.  Otherwise it includes \c \<inotifytools/inotify-nosys.h\>.
 *
 * @section example Example
 * This very simple program recursively watches the entire directory tree
 * under its working directory for events, then prints them out with a
 * timestamp.
 * @include example.c
 *
 * @section events Events
 *
 * @note This section comes almost verbatim from the inotify(7) man page.
 *
 * @warning The information here applies to inotify in Linux 2.6.17.  Older
 *          versions of Linux may not support all the events described here.
 *
 * The following numeric events can be specified to functions in inotifytools,
 * and may be present in events returned through inotifytools:
 *
 * \li \c IN_ACCESS     -     File was accessed (read) \a *
 * \li \c IN_ATTRIB     -     Metadata changed (permissions, timestamps,
 *                            extended attributes, etc.) \a *
 * \li \c IN_CLOSE_WRITE -    File opened for writing was closed \a *
 * \li \c IN_CLOSE_NOWRITE -   File not opened for writing was closed \a *
 * \li \c IN_CREATE       -   File/directory created in watched directory \a *
 * \li \c IN_DELETE       -   File/directory deleted from watched directory \a *
 * \li \c IN_DELETE_SELF  -   Watched file/directory was itself deleted
 * \li \c IN_MODIFY       -   File was modified \a *
 * \li \c IN_MOVE_SELF    -   Watched file/directory was itself moved
 * \li \c IN_MOVED_FROM   -   File moved out of watched directory \a *
 * \li \c IN_MOVED_TO     -   File moved into watched directory \a *
 * \li \c IN_OPEN         -   File was opened \a *
 *
 * When monitoring a directory, the events marked with an asterisk \a * above
 * can  occur  for files  in the directory, in which case the name field in the
 * returned inotify_event structure identifies the name of the file within the
 * directory.
 *
 * The IN_ALL_EVENTS macro is defined as a bit mask of all of the above events.
 *
 * Two additional convenience macros are IN_MOVE, which equates to
 * IN_MOVED_FROM|IN_MOVED_TO, and IN_CLOSE which equates to
 * IN_CLOSE_WRITE|IN_CLOSE_NOWRITE.
 *
 * The following bitmasks can also be provided when creating a new watch:
 *
 * \li \c IN_DONT_FOLLOW  - Don't dereference pathname if it is a symbolic link
 * \li \c IN_MASK_ADD    -  Add (OR) events to watch mask for this pathname if
 *                          it already exists (instead of replacing mask)
 * \li \c IN_ONESHOT    -   Monitor pathname for one event, then remove from
 *                          watch list
 * \li \c IN_ONLYDIR    -   Only watch pathname if it is a directory
 *
 * The following bitmasks may occur in events generated by a watch:
 *
 * \li \c IN_IGNORED   -   Watch was removed explicitly
 *                        (inotifytools_remove_watch_*) or automatically (file
 *                        was deleted, or file system was unmounted)
 * \li \c IN_ISDIR   -     Subject of this event is a directory
 * \li \c IN_Q_OVERFLOW  - Event queue overflowed (wd is -1 for this event)
 * \li \c IN_UNMOUNT    -  File system containing watched object was unmounted
 *
 * @section TODO TODO list
 *
 * @todo Improve wd/filename mapping.  Currently there is no explicit code for
 *       handling different filenames mapping to the same inode (and hence, wd).
 *       gamin's approach sounds good: let the user watch an inode using several
 *       different filenames, and when an event occurs on the inode, generate an
 *       event for each filename.
 */

#define MAX_EVENTS 4096
#define MAX_STRLEN 4096
#define INOTIFY_PROCDIR "/proc/sys/fs/inotify/"
#define WATCHES_SIZE_PATH INOTIFY_PROCDIR "max_user_watches"
#define QUEUE_SIZE_PATH   INOTIFY_PROCDIR "max_queued_watches"
#define INSTANCES_PATH    INOTIFY_PROCDIR "max_user_instances"

static int inotify_fd;
static unsigned  num_access;
static unsigned  num_modify;
static unsigned  num_attrib;
static unsigned  num_close_nowrite;
static unsigned  num_close_write;
static unsigned  num_open;
static unsigned  num_move_self;
static unsigned  num_moved_to;
static unsigned  num_moved_from;
static unsigned  num_create;
static unsigned  num_delete;
static unsigned  num_delete_self;
static unsigned  num_unmount;
static unsigned  num_total;
static int collect_stats = 0;

struct rbtree *tree_wd = 0;
struct rbtree *tree_filename = 0;
static int error = 0;
static int init = 0;
static char* timefmt = 0;
static regex_t* regex = 0;
/* 0: --exclude[i], 1: --include[i] */
static int invert_regexp = 0;

static int isdir( char const * path );
void record_stats( struct inotify_event const * event );
int onestr_to_event(char const * event);

/**
 * @internal
 * Assert that a condition evaluates to true, and optionally output a message
 * if the assertion fails.
 *
 * @param  cond  Integer; if 0, assertion fails, otherwise assertion succeeds.
 *
 * @param  mesg  A human-readable error message shown if assertion fails.
 *
 * @section example Example
 * @code
 * int upper = 100, lower = 50;
 * int input = get_user_input();
 * niceassert( input <= upper && input >= lower,
 *             "input not in required range!");
 * @endcode
 */
#define niceassert(cond,mesg) _niceassert((long)cond, __LINE__, __FILE__, \
                                          #cond, mesg)

#define nasprintf(...) niceassert( -1 != asprintf(__VA_ARGS__), "out of memory")

/**
 * @internal
 * Assert that a condition evaluates to true, and optionally output a message
 * if the assertion fails.
 *
 * You should use the niceassert() preprocessor macro instead.
 *
 * @param  cond  If 0, assertion fails, otherwise assertion succeeds.
 *
 * @param  line  Line number of source code where assertion is made.
 *
 * @param  file  Name of source file where assertion is made.
 *
 * @param  condstr  Stringified assertion expression.
 *
 * @param  mesg  A human-readable error message shown if assertion fails.
 */
static void _niceassert( long cond, int line, char const * file,
                  char const * condstr, char const * mesg ) {
	if ( cond ) return;

	if ( mesg ) {
		fprintf(stderr, "%s:%d assertion ( %s ) failed: %s\n", file, line,
		        condstr, mesg );
	}
	else {
		fprintf(stderr, "%s:%d assertion ( %s ) failed.\n", file, line, condstr);
	}
}

/**
 * @internal
 * Construct a string from a character.
 *
 * @param ch A character.
 *
 * @return A string of length 1 consisting of the character @a ch.  The string
 *         will be overwritten in subsequent calls.
 */
char * chrtostr(char ch) {
	static char str[2] = { '\0', '\0' };
	str[0] = ch;
	return str;
}

/**
 * @internal
 */
int read_num_from_file( char * filename, int * num ) {
	FILE * file = fopen( filename, "r" );
	if ( !file ) {
		error = errno;
		return 0;
	}

	if ( EOF == fscanf( file, "%d", num ) ) {
		error = errno;
		return 0;
	}

	niceassert( 0 == fclose( file ), 0 );

	return 1;
}

int wd_compare(const void *d1, const void *d2, const void *config) {
	if (!d1 || !d2) return d1 - d2;
	return ((watch*)d1)->wd - ((watch*)d2)->wd;
}

int filename_compare(const void *d1, const void *d2, const void *config) {
	if (!d1 || !d2) return d1 - d2;
	return strcmp(((watch*)d1)->filename, ((watch*)d2)->filename);
}

/**
 * @internal
 */
watch *watch_from_wd( int wd ) {
	watch w;
	w.wd = wd;
	return (watch*)rbfind(&w, tree_wd);
}

/**
 * @internal
 */
watch *watch_from_filename( char const *filename ) {
	watch w;
	w.filename = (char*)filename;
	return (watch*)rbfind(&w, tree_filename);
}

/**
 * Initialise inotify.
 *
 * You must call this function before using any function which adds or removes
 * watches or attempts to access any information about watches.
 *
 * @return 1 on success, 0 on failure.  On failure, the error can be
 *         obtained from inotifytools_error().
 */
int inotifytools_initialize() {
	if (init) return 1;

	error = 0;
	// Try to initialise inotify
	inotify_fd = inotify_init();
	if (inotify_fd < 0)	{
		error = errno;
		return 0;
	}

	collect_stats = 0;
	init = 1;
	tree_wd = rbinit(wd_compare, 0);
	tree_filename = rbinit(filename_compare, 0);
	timefmt = 0;

	return 1;
}

/**
 * @internal
 */
void destroy_watch(watch *w) {
	if (w->filename) free(w->filename);
	free(w);
}

/**
 * @internal
 */
void cleanup_tree(const void *nodep,
                 const VISIT which,
                 const int depth, void* arg) {
	if (which != endorder && which != leaf) return;
	watch *w = (watch*)nodep;
	destroy_watch(w);
}

/**
 * Close inotify and free the memory used by inotifytools.
 *
 * If you call this function, you must call inotifytools_initialize()
 * again before any other functions can be used.
 */
void inotifytools_cleanup() {
	if (!init) return;

	init = 0;
	close(inotify_fd);
	collect_stats = 0;
	error = 0;
	timefmt = 0;

	if (regex) {
		regfree(regex);
		free(regex);
		regex = 0;
	}

	rbwalk(tree_wd, cleanup_tree, 0);
	rbdestroy(tree_wd); tree_wd = 0;
	rbdestroy(tree_filename); tree_filename = 0;
}

/**
 * @internal
 */
void empty_stats(const void *nodep,
                 const VISIT which,
                 const int depth, void *arg) {
    if (which != endorder && which != leaf) return;
	watch *w = (watch*)nodep;
	w->hit_access = 0;
	w->hit_modify = 0;
	w->hit_attrib = 0;
	w->hit_close_nowrite = 0;
	w->hit_close_write = 0;
	w->hit_open = 0;
	w->hit_move_self = 0;
	w->hit_moved_from = 0;
	w->hit_moved_to = 0;
	w->hit_create = 0;
	w->hit_delete = 0;
	w->hit_delete_self = 0;
	w->hit_unmount = 0;
	w->hit_total = 0;
}

/**
 * @internal
 */
struct replace_filename_data {
    char const *old_name;
    char const *new_name;
    size_t old_len;
};

/**
 * @internal
 */
void replace_filename(const void *nodep, const VISIT which, const int depth,
                      const struct replace_filename_data *data) {
    if (which != endorder && which != leaf) return;
	watch *w = (watch*)nodep;
	char *name;
	if ( 0 == strncmp( data->old_name, w->filename, data->old_len ) ) {
		nasprintf( &name, "%s%s", data->new_name, &(w->filename[data->old_len]) );
		if (!strcmp( w->filename, data->new_name )) {
			free(name);
		} else {
			rbdelete(w, tree_filename);
			free( w->filename );
			w->filename = name;
			rbsearch(w, tree_filename);
		}
	}
}

/**
 * @internal
 */
void get_num(const void *nodep,
             const VISIT which,
             const int depth, void *arg) {
    if (which != endorder && which != leaf) return;
	++(*((int*)arg));
}


/**
 * Initialize or reset statistics.
 *
 * inotifytools_initialize() must be called before this function can
 * be used.
 *
 * When this function is called, all subsequent events will be tallied.
 * Statistics can then be obtained via the @a inotifytools_get_stat_* functions.
 *
 * After the first call, subsequent calls to this function will reset the
 * event tallies to 0.
 */
void inotifytools_initialize_stats() {
	niceassert( init, "inotifytools_initialize not called yet" );

	// if already collecting stats, reset stats
	if (collect_stats) {
		rbwalk(tree_wd, empty_stats, 0);
	}

	num_access = 0;
	num_modify = 0;
	num_attrib = 0;
	num_close_nowrite = 0;
	num_close_write = 0;
	num_open = 0;
	num_move_self = 0;
	num_moved_from = 0;
	num_moved_to = 0;
	num_create = 0;
	num_delete = 0;
	num_delete_self = 0;
	num_unmount = 0;
	num_total = 0;

	collect_stats = 1;
}

/**
 * Convert character separated events from string form to integer form
 * (as in inotify.h).
 *
 * @param    event    a sequence of events in string form as defined in
 *                    inotify.h without leading IN_ prefix (e.g., MODIFY,
 *                    ATTRIB), separated by the @a sep character.  Case
 *                    insensitive.  Can be a single event.
 *                    Can be empty or NULL.  See section \ref events.
 *
 * @param    sep      Character used to separate events.  @a sep must not be
 *                    a character in a-z, A-Z, or _.
 *
 * @return            integer representing the mask specified by @a event, or 0
 *                    if any string in @a event is empty or NULL, or -1 if
 *                    any string in @a event does not match any event or
 *                    @a sep is invalid.
 *
 * @section example Example
 * @code
 * char * eventstr = "MODIFY:CLOSE:CREATE";
 * int eventnum = inotifytools_str_to_event_sep( eventstr, ':' );
 * if ( eventnum == IN_MODIFY | IN_CLOSE | IN_CREATE ) {
 *    printf( "This code always gets executed!\n" );
 * }
 * @endcode
 */
int inotifytools_str_to_event_sep(char const * event, char sep) {
	if ( strchr( "_" "abcdefghijklmnopqrstuvwxyz"
	                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ", sep ) ) {
		return -1;
	}

	int ret, ret1, len;
	char * event1, * event2;
        static const size_t eventstr_size = 4096;
        char eventstr[eventstr_size];
        ret = 0;

	if ( !event || !event[0] ) return 0;

	event1 = (char *)event;
	event2 = strchr( event1, sep );
	while ( event1 && event1[0] ) {
		if ( event2 ) {
			len = event2 - event1;
                        niceassert(len < eventstr_size,
                                   "malformed event string (very long)");
                }
		else {
			len = strlen(event1);
		}
                if (len > eventstr_size - 1)
                    len = eventstr_size - 1;

                if (event2 || len == eventstr_size - 1) {
                    strncpy(eventstr, event1, len);
                } else {
                    strcpy(eventstr, event1);
                }

                eventstr[len] = 0;

		ret1 = onestr_to_event( eventstr );
		if ( 0 == ret1 || -1 == ret1 ) {
			ret = ret1;
			break;
		}
		ret |= ret1;

		event1 = event2;
		if ( event1 && event1[0] ) {
			// jump over 'sep' character
			++event1;
			// if last character was 'sep'...
			if ( !event1[0] ) return 0;
			event2 = strchr( event1, sep );
		}
	}

	return ret;
}

/**
 * Convert comma-separated events from string form to integer form
 * (as in inotify.h).
 *
 * @param    event    a sequence of events in string form as defined in
 *                    inotify.h without leading IN_ prefix (e.g., MODIFY,
 *                    ATTRIB), comma-separated.  Case
 *                    insensitive.  Can be a single event.
 *                    Can be empty or NULL.  See section \ref events.
 *
 * @return            integer representing the mask specified by @a event, or 0
 *                    if any string in @a event is empty or NULL, or -1 if
 *                    any string in @a event does not match any event.
 *
 * @section example Example
 * @code
 * char * eventstr = "MODIFY,CLOSE,CREATE";
 * int eventnum = inotifytools_str_to_event( eventstr );
 * if ( eventnum == IN_MODIFY | IN_CLOSE | IN_CREATE ) {
 *    printf( "This code always gets executed!\n" );
 * }
 * @endcode
 */
int inotifytools_str_to_event(char const * event) {
	return inotifytools_str_to_event_sep( event, ',' );
}

/**
 * @internal
 * Convert a single event from string form to integer form (as in inotify.h).
 *
 * @param    event    event in string form as defined in inotify.h without
 *                    leading IN_ prefix (e.g., MODIFY, ATTRIB).  Case
 *                    insensitive.  Can be empty or NULL.
 * @return            integer representing the mask specified by 'event', or 0
 *                    if @a event is empty or NULL, or -1 if string does not
 *                    match any event.
 */
int onestr_to_event(char const * event)
{
	static int ret;
	ret = -1;

	if ( !event || !event[0] )
		ret = 0;
	else if ( 0 == strcasecmp(event, "ACCESS") )
		ret = IN_ACCESS;
	else if ( 0 == strcasecmp(event, "MODIFY") )
		ret = IN_MODIFY;
	else if ( 0 == strcasecmp(event, "ATTRIB") )
		ret = IN_ATTRIB;
	else if ( 0 == strcasecmp(event, "CLOSE_WRITE") )
		ret = IN_CLOSE_WRITE;
	else if ( 0 == strcasecmp(event, "CLOSE_NOWRITE") )
		ret = IN_CLOSE_NOWRITE;
	else if ( 0 == strcasecmp(event, "OPEN") )
		ret = IN_OPEN;
	else if ( 0 == strcasecmp(event, "MOVED_FROM") )
		ret = IN_MOVED_FROM;
	else if ( 0 == strcasecmp(event, "MOVED_TO") )
		ret = IN_MOVED_TO;
	else if ( 0 == strcasecmp(event, "CREATE") )
		ret = IN_CREATE;
	else if ( 0 == strcasecmp(event, "DELETE") )
		ret = IN_DELETE;
	else if ( 0 == strcasecmp(event, "DELETE_SELF") )
		ret = IN_DELETE_SELF;
	else if ( 0 == strcasecmp(event, "UNMOUNT") )
		ret = IN_UNMOUNT;
	else if ( 0 == strcasecmp(event, "Q_OVERFLOW") )
		ret = IN_Q_OVERFLOW;
	else if ( 0 == strcasecmp(event, "IGNORED") )
		ret = IN_IGNORED;
	else if ( 0 == strcasecmp(event, "CLOSE") )
		ret = IN_CLOSE;
	else if ( 0 == strcasecmp(event, "MOVE_SELF") )
		ret = IN_MOVE_SELF;
	else if ( 0 == strcasecmp(event, "MOVE") )
		ret = IN_MOVE;
	else if ( 0 == strcasecmp(event, "ISDIR") )
		ret = IN_ISDIR;
	else if ( 0 == strcasecmp(event, "ONESHOT") )
		ret = IN_ONESHOT;
	else if ( 0 == strcasecmp(event, "ALL_EVENTS") )
		ret = IN_ALL_EVENTS;

	return ret;
}

/**
 * Convert event from integer form to string form (as in inotify.h).
 *
 * The returned string is from static storage; subsequent calls to this function
 * or inotifytools_event_to_str_sep() will overwrite it.  Don't free() it and
 * make a copy if you want to keep it.
 *
 * @param    events   OR'd event(s) in integer form as defined in inotify.h.
 *                    See section \ref events.
 *
 * @return            comma-separated string representing the event(s), in no
 *                    particular order
 *
 * @section example Example
 * @code
 * int eventnum == IN_MODIFY | IN_CLOSE | IN_CREATE;
 * char * eventstr = inotifytools_event_to_str( eventnum );
 * printf( "%s\n", eventstr );
 * // outputs something like MODIFY,CLOSE,CREATE but order not guaranteed.
 * @endcode
 */
char * inotifytools_event_to_str(int events) {
	return inotifytools_event_to_str_sep(events, ',');
}

/**
 * Convert event from integer form to string form (as in inotify.h).
 *
 * The returned string is from static storage; subsequent calls to this function
 * or inotifytools_event_to_str() will overwrite it.  Don't free() it and
 * make a copy if you want to keep it.
 *
 * @param    events   OR'd event(s) in integer form as defined in inotify.h
 *
 * @param    sep      character used to separate events
 *
 * @return            @a sep separated string representing the event(s), in no
 *                    particular order.  If the integer is not made of OR'ed
 *                    inotify events, the string returned will be a hexadecimal
 *                    representation of the integer.
 *
 * @section example Example
 * @code
 * int eventnum == IN_MODIFY | IN_CLOSE | IN_CREATE;
 * char * eventstr = inotifytools_event_to_str_sep( eventnum, '-' );
 * printf( "%s\n", eventstr );
 * // outputs something like MODIFY-CLOSE-CREATE but order not guaranteed.
 * @endcode
 */
char * inotifytools_event_to_str_sep(int events, char sep)
{
	static char ret[1024];
	ret[0] = '\0';
	ret[1] = '\0';

	if ( IN_ACCESS & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "ACCESS" );
	}
	if ( IN_MODIFY & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "MODIFY" );
	}
	if ( IN_ATTRIB & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "ATTRIB" );
	}
	if ( IN_CLOSE_WRITE & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "CLOSE_WRITE" );
	}
	if ( IN_CLOSE_NOWRITE & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "CLOSE_NOWRITE" );
	}
	if ( IN_OPEN & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "OPEN" );
	}
	if ( IN_MOVED_FROM & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "MOVED_FROM" );
	}
	if ( IN_MOVED_TO & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "MOVED_TO" );
	}
	if ( IN_CREATE & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "CREATE" );
	}
	if ( IN_DELETE & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "DELETE" );
	}
	if ( IN_DELETE_SELF & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "DELETE_SELF" );
	}
	if ( IN_UNMOUNT & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "UNMOUNT" );
	}
	if ( IN_Q_OVERFLOW & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "Q_OVERFLOW" );
	}
	if ( IN_IGNORED & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "IGNORED" );
	}
	if ( IN_CLOSE & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "CLOSE" );
	}
	if ( IN_MOVE_SELF & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "MOVE_SELF" );
	}
	if ( IN_ISDIR & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "ISDIR" );
	}
	if ( IN_ONESHOT & events ) {
		strcat( ret, chrtostr(sep) );
		strcat( ret, "ONESHOT" );
	}

	// Maybe we didn't match any... ?
	if (ret[0] == '\0') {
		niceassert( -1 != sprintf( ret, "%c0x%08x", sep, events ), 0 );
	}

	return &ret[1];
}

/**
 * Get the filename used to establish a watch.
 *
 * inotifytools_initialize() must be called before this function can
 * be used.
 *
 * @param wd watch descriptor.
 *
 * @return filename associated with watch descriptor @a wd, or NULL if @a wd
 *         is not associated with any filename.
 *
 * @note This always returns the filename which was used to establish a watch.
 *       This means the filename may be a relative path.  If this isn't desired,
 *       then always use absolute paths when watching files.
 *       Also, this is not necessarily the filename which might have been used
 *       to cause an event on the file, since inotify is inode based and there
 *       can be many filenames mapping to a single inode.
 *       Finally, if a file is moved or renamed while being watched, the
 *       filename returned will still be the original name.
 */
char * inotifytools_filename_from_wd( int wd ) {
	niceassert( init, "inotifytools_initialize not called yet" );
	watch *w = watch_from_wd(wd);
	if (!w)
        return NULL;

	return w->filename;
}

/**
 * Get the watch descriptor for a particular filename.
 *
 * inotifytools_initialize() must be called before this function can
 * be used.
 *
 * @param filename file name to find watch descriptor for.
 *
 * @return watch descriptor associated with filename, or -1 if @a filename is
 *         not associated with any watch descriptor.
 *
 * @note The filename specified must always be the original name used to
 *       establish the watch.
 */
int inotifytools_wd_from_filename( char const * filename ) {
	niceassert( init, "inotifytools_initialize not called yet" );
	watch *w = watch_from_filename(filename);
	if (!w) return -1;
	return w->wd;
}

/**
 * Set the filename for a particular watch descriptor.
 *
 * This function should be used to update a filename when a file is known to
 * have been moved or renamed.  At the moment, libinotifytools does not
 * automatically handle this situation.
 *
 * inotifytools_initialize() must be called before this function can
 * be used.
 *
 * @param wd Watch descriptor.
 *
 * @param filename New filename.
 */
void inotifytools_set_filename_by_wd( int wd, char const * filename ) {
	niceassert( init, "inotifytools_initialize not called yet" );
	watch *w = watch_from_wd(wd);
	if (!w) return;
	if (w->filename) free(w->filename);
	w->filename = strdup(filename);
}

/**
 * Set the filename for one or more watches with a particular existing filename.
 *
 * This function should be used to update a filename when a file is known to
 * have been moved or renamed.  At the moment, libinotifytools does not
 * automatically handle this situation.
 *
 * inotifytools_initialize() must be called before this function can
 * be used.
 *
 * @param oldname Current filename.
 *
 * @param newname New filename.
 */
void inotifytools_set_filename_by_filename( char const * oldname,
                                            char const * newname ) {
	watch *w = watch_from_filename(oldname);
	if (!w) return;
	if (w->filename) free(w->filename);
	w->filename = strdup(newname);
}

/**
 * Replace a certain filename prefix on all watches.
 *
 * This function should be used to update filenames for an entire directory tree
 * when a directory is known to have been moved or renamed.  At the moment,
 * libinotifytools does not automatically handle this situation.
 *
 * inotifytools_initialize() must be called before this function can
 * be used.
 *
 * @param oldname Current filename prefix.
 *
 * @param newname New filename prefix.
 *
 * @section example Example
 * @code
 * // if /home/user1/original_dir is moved to /home/user2/new_dir, then to
 * // update all watches:
 * inotifytools_replace_filename( "/home/user1/original_dir",
 *                                "/home/user2/new_dir" );
 * @endcode
 */
void inotifytools_replace_filename( char const * oldname,
                                    char const * newname ) {
	if ( !oldname || !newname ) return;
	struct replace_filename_data data;
	data.old_name = oldname;
	data.new_name = newname;
	data.old_len = strlen(oldname);
        rbwalk(tree_filename, (void *)replace_filename, (void *)&data);
}

/**
 * @internal
 */
int remove_inotify_watch(watch *w) {
	error = 0;
	int status = inotify_rm_watch( inotify_fd, w->wd );
	if ( status < 0 ) {
		fprintf(stderr, "Failed to remove watch on %s: %s\n", w->filename,
		        strerror(status) );
		error = status;
		return 0;
	}
	return 1;
}

/**
 * @internal
 */
watch *create_watch(int wd, char *filename) {
	if ( wd <= 0 || !filename) return 0;

	watch *w = (watch*)calloc(1, sizeof(watch));
	w->wd = wd;
	w->filename = strdup(filename);
	rbsearch(w, tree_wd);
	rbsearch(w, tree_filename);
    return NULL;
}

/**
 * Remove a watch on a file specified by watch descriptor.
 *
 * inotifytools_initialize() must be called before this function can
 * be used.
 *
 * @param wd Watch descriptor of watch to be removed.
 *
 * @return 1 on success, 0 on failure.  If the given watch doesn't exist,
 *         returns 1.  On failure, the error can be
 *         obtained from inotifytools_error().
 */
int inotifytools_remove_watch_by_wd( int wd ) {
	niceassert( init, "inotifytools_initialize not called yet" );
	watch *w = watch_from_wd(wd);
	if (!w) return 1;

	if (!remove_inotify_watch(w)) return 0;
	rbdelete(w, tree_wd);
	rbdelete(w, tree_filename);
	destroy_watch(w);
	return 1;
}

/**
 * Remove a watch on a file specified by filename.
 *
 * @param filename Name of file on which watch should be removed.
 *
 * @return 1 on success, 0 on failure.  On failure, the error can be
 *         obtained from inotifytools_error().
 *
 * @note The filename specified must always be the original name used to
 *       establish the watch.
 */
int inotifytools_remove_watch_by_filename( char const * filename ) {
	niceassert( init, "inotifytools_initialize not called yet" );
	watch *w = watch_from_filename(filename);
	if (!w) return 1;

	if (!remove_inotify_watch(w)) return 0;
	rbdelete(w, tree_wd);
	rbdelete(w, tree_filename);
	destroy_watch(w);
	return 1;
}

/**
 * Set up a watch on a file.
 *
 * @param filename Absolute or relative path of file to watch.
 *
 * @param events bitwise ORed inotify events to watch for.  See section
 *               \ref events.
 *
 * @return 1 on success, 0 on failure.  On failure, the error can be
 *         obtained from inotifytools_error().
 */
int inotifytools_watch_file( char const * filename, int events ) {
	static char const * filenames[2];
	filenames[0] = filename;
	filenames[1] = NULL;
	return inotifytools_watch_files( filenames, events );
}

/**
 * Set up a watch on a list of files.
 *
 * inotifytools_initialize() must be called before this function can
 * be used.
 *
 * @param filenames null-terminated array of absolute or relative paths of
 *                  files to watch.
 *
 * @param events bitwise OR'ed inotify events to watch for.  See section
 *               \ref events.
 *
 * @return 1 on success, 0 on failure.  On failure, the error can be
 *         obtained from inotifytools_error().
 */
int inotifytools_watch_files( char const * filenames[], int events ) {
	niceassert( init, "inotifytools_initialize not called yet" );
	error = 0;

	static int i;
	for ( i = 0; filenames[i]; ++i ) {
		static int wd;
		wd = inotify_add_watch( inotify_fd, filenames[i], events );
		if ( wd < 0 ) {
			if ( wd == -1 ) {
				error = errno;
				return 0;
			} // if ( wd == -1 )
			else {
				fprintf( stderr, "Failed to watch %s: returned wd was %d "
				         "(expected -1 or >0 )", filenames[i], wd );
				// no appropriate value for error
				return 0;
			} // else
		} // if ( wd < 0 )

		char *filename;
		// Always end filename with / if it is a directory
		if ( !isdir(filenames[i])
		     || filenames[i][strlen(filenames[i])-1] == '/') {
			filename = strdup(filenames[i]);
		}
		else {
			nasprintf( &filename, "%s/", filenames[i] );
		}
		create_watch(wd, filename);
		free(filename);
	} // for

	return 1;
}

/**
 * Get the next inotify event to occur.
 *
 * inotifytools_initialize() must be called before this function can
 * be used.
 *
 * @param timeout maximum amount of time, in seconds, to wait for an event.
 *                If @a timeout is non-negative, the function is non-blocking.
 *                If @a timeout is negative, the function will block until an
 *                event occurs.
 *
 * @return pointer to an inotify event, or NULL if function timed out before
 *         an event occurred.  The event is located in static storage and it
 *         may be overwritten in subsequent calls; do not call free() on it,
 *         and make a copy if you want to keep it.
 *
 * @note Your program should call this function or
 *       inotifytools_next_events() frequently; between calls to this function,
 *       inotify events will be queued in the kernel, and eventually the queue
 *       will overflow and you will miss some events.
 *
 * @note If the function inotifytools_ignore_events_by_regex() has been called
 *       with a non-NULL parameter, this function will not return on events
 *       which match the regular expression passed to that function.  However,
 *       the @a timeout period begins again each time a matching event occurs.
 */
struct inotify_event * inotifytools_next_event( long int timeout ) {
	return inotifytools_next_events( timeout, 1 );
}


/**
 * Get the next inotify events to occur.
 *
 * inotifytools_initialize() must be called before this function can
 * be used.
 *
 * @param timeout maximum amount of time, in seconds, to wait for an event.
 *                If @a timeout is non-negative, the function is non-blocking.
 *                If @a timeout is negative, the function will block until an
 *                event occurs.
 *
 * @param num_events approximate number of inotify events to wait for until
 *                   this function returns.  Use this for buffering reads to
 *                   inotify if you expect to receive large amounts of events.
 *                   You are NOT guaranteed that this number of events will
 *                   actually be read; instead, you are guaranteed that the
 *                   number of bytes read from inotify is
 *                   @a num_events * sizeof(struct inotify_event).  Obviously
 *                   the larger this number is, the greater the latency between
 *                   when an event occurs and when you'll know about it.
 *                   May not be larger than 4096.
 *
 * @return pointer to an inotify event, or NULL if function timed out before
 *         an event occurred or @a num_events < 1.  The event is located in
 *         static storage and it may be overwritten in subsequent calls; do not
 *         call free() on it, and make a copy if you want to keep it.
 *         When @a num_events is greater than 1, this will return a pointer to
 *         the first event only, and you MUST call this function again to
 *         get pointers to subsequent events; don't try to add to the pointer
 *         to find the next events or you will run into trouble.
 *
 * @note You may actually get different events with different values of
 *       @a num_events.  This is because inotify does some in-kernel filtering
 *       of duplicate events, meaning some duplicate events will not be
 *       reported if @a num_events > 1.  For some purposes this is fine, but
 *       for others (such as gathering accurate statistics on numbers of event
 *       occurrences) you must call this function with @a num_events = 1, or
 *       simply use inotifytools_next_event().
 *
 * @note Your program should call this function frequently; between calls to this
 *       function, inotify events will be queued in the kernel, and eventually
 *       the queue will overflow and you will miss some events.
 *
 * @note If the function inotifytools_ignore_events_by_regex() has been called
 *       with a non-NULL parameter, this function will not return on events
 *       which match the regular expression passed to that function.  However,
 *       the @a timeout period begins again each time a matching event occurs.
 */
struct inotify_event * inotifytools_next_events( long int timeout, int num_events ) {
	niceassert( init, "inotifytools_initialize not called yet" );
	niceassert( num_events <= MAX_EVENTS, "too many events requested" );

	if ( num_events < 1 ) return NULL;

	static struct inotify_event event[MAX_EVENTS];
	static struct inotify_event * ret;
	static int first_byte = 0;
	static ssize_t bytes;
	static jmp_buf jmp;
	static char match_name[MAX_STRLEN];

#define RETURN(A) {\
	if (regex) {\
		inotifytools_snprintf(match_name, MAX_STRLEN, A, "%w%f");\
		if (0 == regexec(regex, match_name, 0, 0, 0)) {\
			if (!invert_regexp)\
				longjmp(jmp,0);\
		} else {\
			if (invert_regexp)\
				longjmp(jmp,0);\
		}\
	}\
	if ( collect_stats ) {\
		record_stats( A );\
	}\
	return A;\
}

	setjmp(jmp);

	error = 0;

	// first_byte is index into event buffer
	if ( first_byte != 0
	  && first_byte <= (int)(bytes - sizeof(struct inotify_event)) ) {

		ret = (struct inotify_event *)((char *)&event[0] + first_byte);
		first_byte += sizeof(struct inotify_event) + ret->len;

		// if the pointer to the next event exactly hits end of bytes read,
		// that's good.  next time we're called, we'll read.
		if ( first_byte == bytes ) {
			first_byte = 0;
		}
		else if ( first_byte > bytes ) {
			// oh... no.  this can't be happening.  An incomplete event.
			// Copy what we currently have into first element, call self to
			// read remainder.
			// oh, and they BETTER NOT overlap.
			// Boy I hope this code works.
			// But I think this can never happen due to how inotify is written.
			niceassert( (long)((char *)&event[0] +
			            sizeof(struct inotify_event) +
			            event[0].len) <= (long)ret,
			            "extremely unlucky user, death imminent" );
			// how much of the event do we have?
			bytes = (char *)&event[0] + bytes - (char *)ret;
			memcpy( &event[0], ret, bytes );
			return inotifytools_next_events( timeout, num_events );
		}
		RETURN(ret);

	}

	else if ( first_byte == 0 ) {
		bytes = 0;
	}


	static ssize_t this_bytes;
	static unsigned int bytes_to_read;
	static int rc;
	static fd_set read_fds;

	static struct timeval read_timeout;
	read_timeout.tv_sec = timeout;
	read_timeout.tv_usec = 0;
	static struct timeval * read_timeout_ptr;
	read_timeout_ptr = ( timeout < 0 ? NULL : &read_timeout );

	FD_ZERO(&read_fds);
	FD_SET(inotify_fd, &read_fds);
	rc = select(inotify_fd + 1, &read_fds,
	            NULL, NULL, read_timeout_ptr);
	if ( rc < 0 ) {
		// error
		error = errno;
		return NULL;
	}
	else if ( rc == 0 ) {
		// timeout
		return NULL;
	}

	// wait until we have enough bytes to read
	do {
		rc = ioctl( inotify_fd, FIONREAD, &bytes_to_read );
	} while ( !rc &&
	          bytes_to_read < sizeof(struct inotify_event)*num_events );

	if ( rc == -1 ) {
		error = errno;
		return NULL;
	}

	this_bytes = read(inotify_fd, &event[0] + bytes,
	                  sizeof(struct inotify_event)*MAX_EVENTS - bytes);
	if ( this_bytes < 0 ) {
		error = errno;
		return NULL;
	}
	if ( this_bytes == 0 ) {
		fprintf(stderr, "Inotify reported end-of-file.  Possibly too many "
		                "events occurred at once.\n");
		return NULL;
	}
	bytes += this_bytes;

	ret = &event[0];
	first_byte = sizeof(struct inotify_event) + ret->len;
	niceassert( first_byte <= bytes, "ridiculously long filename, things will "
	                                 "almost certainly screw up." );
	if ( first_byte == bytes ) {
		first_byte = 0;
	}

	RETURN(ret);

#undef RETURN
}

/**
 * Set up recursive watches on an entire directory tree.
 *
 * inotifytools_initialize() must be called before this function can
 * be used.
 *
 * @param path path of directory or file to watch.  If the path is a directory,
 *             every subdirectory will also be watched for the same events up
 *             to the maximum readable depth.  If the path is a file, the file
 *             is watched exactly as if inotifytools_watch_file() were used.
 *
 * @param events Inotify events to watch for.  See section \ref events.
 *
 * @return 1 on success, 0 on failure.  On failure, the error can be
 *         obtained from inotifytools_error().  Note that some errors on
 *         subdirectories will be ignored; for example, if you watch a directory
 *         tree which contains some directories which you do not have access to,
 *         those directories will not be watched, but this function will still
 *         return 1 if no other errors occur.
 *
 * @note This function does not attempt to work atomically.  If you use this
 *       function to watch a directory tree and files or directories are being
 *       created or removed within that directory tree, there are no guarantees
 *       as to whether or not those files will be watched.
 */
int inotifytools_watch_recursively( char const * path, int events ) {
	return inotifytools_watch_recursively_with_exclude( path, events, 0 );
}

/**
 * Set up recursive watches on an entire directory tree, optionally excluding
 * some directories.
 *
 * inotifytools_initialize() must be called before this function can
 * be used.
 *
 * @author UH
 *
 * @param path path of directory or file to watch.  If the path is a directory,
 *             every subdirectory will also be watched for the same events up
 *             to the maximum readable depth.  If the path is a file, the file
 *             is watched exactly as if inotifytools_watch_file() were used.
 *
 * @param exclude_list NULL terminated path list of directories not to watch.
 *                     Can be NULL if no paths are to be excluded.
 *                     Directories may or may not include a trailing '/'.
 *
 * @param events Inotify events to watch for.  See section \ref events.
 *
 * @return 1 on success, 0 on failure.  On failure, the error can be
 *         obtained from inotifytools_error().  Note that some errors on
 *         subdirectories will be ignored; for example, if you watch a directory
 *         tree which contains some directories which you do not have access to,
 *         those directories will not be watched, but this function will still
 *         return 1 if no other errors occur.
 *
 * @note This function does not attempt to work atomically.  If you use this
 *       function to watch a directory tree and files or directories are being
 *       created or removed within that directory tree, there are no guarantees
 *       as to whether or not those files will be watched.
 */
int inotifytools_watch_recursively_with_exclude( char const * path, int events,
                                                 char const ** exclude_list ) {
	niceassert( init, "inotifytools_initialize not called yet" );

	DIR * dir;
	char * my_path;
	error = 0;
	dir = opendir( path );
	if ( !dir ) {
		// If not a directory, don't need to do anything special
		if ( errno == ENOTDIR ) {
			return inotifytools_watch_file( path, events );
		}
		else {
			error = errno;
			return 0;
		}
	}

	if ( path[strlen(path)-1] != '/' ) {
		nasprintf( &my_path, "%s/", path );
	}
	else {
		my_path = (char *)path;
	}

	static struct dirent * ent;
	char * next_file;
	static struct stat64 my_stat;
	ent = readdir( dir );
	// Watch each directory within this directory
	while ( ent ) {
		if ( (0 != strcmp( ent->d_name, "." )) &&
		     (0 != strcmp( ent->d_name, ".." )) ) {
			nasprintf(&next_file,"%s%s", my_path, ent->d_name);
			if ( -1 == lstat64( next_file, &my_stat ) ) {
				error = errno;
				free( next_file );
				if ( errno != EACCES ) {
					error = errno;
					if ( my_path != path ) free( my_path );
					closedir( dir );
					return 0;
				}
			}
			else if ( S_ISDIR( my_stat.st_mode ) &&
			          !S_ISLNK( my_stat.st_mode )) {
				free( next_file );
				nasprintf(&next_file,"%s%s/", my_path, ent->d_name);
				static unsigned int no_watch;
				static char const ** exclude_entry;

				no_watch = 0;
				for (exclude_entry = exclude_list;
					 exclude_entry && *exclude_entry && !no_watch;
					 ++exclude_entry) {
					static int exclude_length;

					exclude_length = strlen(*exclude_entry);
					if ((*exclude_entry)[exclude_length-1] == '/') {
						--exclude_length;
					}
					if ( strlen(next_file) == (unsigned)(exclude_length + 1) &&
					    !strncmp(*exclude_entry, next_file, exclude_length)) {
						// directory found in exclude list
						no_watch = 1;
					}
				}
				if (!no_watch) {
					static int status;
					status = inotifytools_watch_recursively_with_exclude(
					              next_file,
					              events,
					              exclude_list );
					// For some errors, we will continue.
					if ( !status && (EACCES != error) && (ENOENT != error) &&
					     (ELOOP != error) ) {
						free( next_file );
						if ( my_path != path ) free( my_path );
						closedir( dir );
						return 0;
					}
				} // if !no_watch
				free( next_file );
			} // if isdir and not islnk
			else {
				free( next_file );
			}
		}
		ent = readdir( dir );
		error = 0;
	}

	closedir( dir );

	int ret = inotifytools_watch_file( my_path, events );
	if ( my_path != path ) free( my_path );
        return ret;
}

/**
 * @internal
 */
void record_stats( struct inotify_event const * event ) {
	if (!event) return;
	watch *w = watch_from_wd(event->wd);
	if (!w) return;
	if ( IN_ACCESS & event->mask ) {
		++w->hit_access;
		++num_access;
	}
	if ( IN_MODIFY & event->mask ) {
		++w->hit_modify;
		++num_modify;
	}
	if ( IN_ATTRIB & event->mask ) {
		++w->hit_attrib;
		++num_attrib;
	}
	if ( IN_CLOSE_WRITE & event->mask ) {
		++w->hit_close_write;
		++num_close_write;
	}
	if ( IN_CLOSE_NOWRITE & event->mask ) {
		++w->hit_close_nowrite;
		++num_close_nowrite;
	}
	if ( IN_OPEN & event->mask ) {
		++w->hit_open;
		++num_open;
	}
	if ( IN_MOVED_FROM & event->mask ) {
		++w->hit_moved_from;
		++num_moved_from;
	}
	if ( IN_MOVED_TO & event->mask ) {
		++w->hit_moved_to;
		++num_moved_to;
	}
	if ( IN_CREATE & event->mask ) {
		++w->hit_create;
		++num_create;
	}
	if ( IN_DELETE & event->mask ) {
		++w->hit_delete;
		++num_delete;
	}
	if ( IN_DELETE_SELF & event->mask ) {
		++w->hit_delete_self;
		++num_delete_self;
	}
	if ( IN_UNMOUNT & event->mask ) {
		++w->hit_unmount;
		++num_unmount;
	}
	if ( IN_MOVE_SELF & event->mask ) {
		++w->hit_move_self;
		++num_move_self;
	}

	++w->hit_total;
	++num_total;

}

unsigned int *stat_ptr(watch *w, int event)
{
	if ( IN_ACCESS == event )
		return &w->hit_access;
	if ( IN_MODIFY == event )
		return &w->hit_modify;
	if ( IN_ATTRIB == event )
		return &w->hit_attrib;
	if ( IN_CLOSE_WRITE == event )
		return &w->hit_close_write;
	if ( IN_CLOSE_NOWRITE == event )
		return &w->hit_close_nowrite;
	if ( IN_OPEN == event )
		return &w->hit_open;
	if ( IN_MOVED_FROM == event )
		return &w->hit_moved_from;
	if ( IN_MOVED_TO == event )
		return &w->hit_moved_to;
	if ( IN_CREATE == event )
		return &w->hit_create;
	if ( IN_DELETE == event )
		return &w->hit_delete;
	if ( IN_DELETE_SELF == event )
		return &w->hit_delete_self;
	if ( IN_UNMOUNT == event )
		return &w->hit_unmount;
	if ( IN_MOVE_SELF == event )
		return &w->hit_move_self;
	if ( 0 == event )
		return &w->hit_total;
	return 0;
}

/**
 * Get statistics by a particular watch descriptor.
 *
 * inotifytools_initialize_stats() must be called before this function can
 * be used.
 *
 * @param wd watch descriptor to get stats for.
 *
 * @param event a single inotify event to get statistics for, or 0 for event
 *              total.  See section \ref events.
 *
 * @return the number of times the event specified by @a event has occurred on
 *         the watch descriptor specified by @a wd since stats collection was
 *         enabled, or -1 if @a event or @a wd are invalid.
 */
int inotifytools_get_stat_by_wd( int wd, int event ) {
	if (!collect_stats) return -1;

	watch *w = watch_from_wd(wd);
	if (!w) return -1;
	unsigned int *i = stat_ptr(w, event);
	if (!i) return -1;
	return *i;
}

/**
 * Get statistics aggregated across all watches.
 *
 * inotifytools_initialize_stats() must be called before this function can
 * be used.
 *
 * @param event a single inotify event to get statistics for, or 0 for event
 *              total.  See section \ref events.
 *
 * @return the number of times the event specified by @a event has occurred over
 *         all watches since stats collection was enabled, or -1 if @a event
 *         is not a valid event.
 */
int inotifytools_get_stat_total( int event ) {
	if (!collect_stats) return -1;
	if ( IN_ACCESS == event )
		return num_access;
	if ( IN_MODIFY == event )
		return num_modify;
	if ( IN_ATTRIB == event )
		return num_attrib;
	if ( IN_CLOSE_WRITE == event )
		return num_close_write;
	if ( IN_CLOSE_NOWRITE == event )
		return num_close_nowrite;
	if ( IN_OPEN == event )
		return num_open;
	if ( IN_MOVED_FROM == event )
		return num_moved_from;
	if ( IN_MOVED_TO == event )
		return num_moved_to;
	if ( IN_CREATE == event )
		return num_create;
	if ( IN_DELETE == event )
		return num_delete;
	if ( IN_DELETE_SELF == event )
		return num_delete_self;
	if ( IN_UNMOUNT == event )
		return num_unmount;
	if ( IN_MOVE_SELF == event )
		return num_move_self;

	if ( 0 == event )
		return num_total;

	return -1;
}

/**
 * Get statistics by a particular filename.
 *
 * inotifytools_initialize_stats() must be called before this function can
 * be used.
 *
 * @param filename name of file to get stats for.
 *
 * @param event a single inotify event to get statistics for, or 0 for event
 *              total.  See section \ref events.
 *
 * @return the number of times the event specified by @a event has occurred on
 *         the file specified by @a filename since stats collection was
 *         enabled, or -1 if the file is not being watched or @a event is
 *         invalid.
 *
 * @note The filename specified must always be the original name used to
 *       establish the watch.
 */
int inotifytools_get_stat_by_filename( char const * filename,
                                                int event ) {
	return inotifytools_get_stat_by_wd( inotifytools_wd_from_filename(
	       filename ), event );
}

/**
 * Get the last error which occurred.
 *
 * When a function fails, call this to find out why.  The returned value is
 * a typical @a errno value, the meaning of which depends on context.  For
 * example, if inotifytools_watch_file() fails because you attempt to watch
 * a file which doesn't exist, this function will return @a ENOENT.
 *
 * @return an error code.
 */
int inotifytools_error() {
	return error;
}

/**
 * @internal
 */
static int isdir( char const * path ) {
	static struct stat64 my_stat;

	if ( -1 == lstat64( path, &my_stat ) ) {
		if (errno == ENOENT) return 0;
		fprintf(stderr, "Stat failed on %s: %s\n", path, strerror(errno));
		return 0;
	}

	return S_ISDIR( my_stat.st_mode ) && !S_ISLNK( my_stat.st_mode );
}


/**
 * Get the number of watches set up through libinotifytools.
 *
 * @return number of watches set up by inotifytools_watch_file(),
 *         inotifytools_watch_files() and inotifytools_watch_recursively().
 */
int inotifytools_get_num_watches() {
	int ret = 0;
	rbwalk(tree_filename, get_num, (void*)&ret);
	return ret;
}

/**
 * Print a string to standard out using an inotify_event and a printf-like
 * syntax.
 * The string written will only ever be up to 4096 characters in length.
 *
 * @param event the event to use to construct a string.
 *
 * @param fmt the format string used to construct a string.
 *
 * @return number of characters written, or -1 if an error occurs.
 *
 * @section syntax Format string syntax
 * The following tokens will be replaced with the specified string:
 *  \li \c \%w - This will be replaced with the name of the Watched file on
 *               which an event occurred.
 *  \li \c \%c - This will be replaced with the cookie of the Watched file on
 *               which an event occurred.
 *  \li \c \%f - When an event occurs within a directory, this will be replaced
 *               with the name of the File which caused the event to occur.
 *               Otherwise, this will be replaced with an empty string.
 *  \li \c \%e - Replaced with the Event(s) which occurred, comma-separated.
 *  \li \c \%Xe - Replaced with the Event(s) which occurred, separated by
 *                whichever character is in the place of `X'.
 *  \li \c \%T - Replaced by the current Time in the format specified by the
 *               string previously passed to inotifytools_set_printf_timefmt(),
 *               or replaced with an empty string if that function has never
 *               been called.
 *
 * @section example Example
 * @code
 * // suppose this is the only file watched.
 * inotifytools_watch_file( "mydir/", IN_CLOSE );
 *
 * // wait until an event occurs
 * struct inotify_event * event = inotifytools_next_event( -1 );
 *
 * inotifytools_printf(stderr, event, "in %w, file %f had event(s): %.e\n");
 * // suppose the file 'myfile' in mydir was read from and closed.  Then,
 * // this prints to standard out something like:
 * // "in mydir/, file myfile had event(s): CLOSE_NOWRITE.CLOSE.ISDIR\n"
 * @endcode
 */
int inotifytools_printf( struct inotify_event* event, char* fmt ) {
	return inotifytools_fprintf( stdout, event, fmt );
}

/**
 * Print a string to a file using an inotify_event and a printf-like syntax.
 * The string written will only ever be up to 4096 characters in length.
 *
 * @param file file to print to
 *
 * @param event the event to use to construct a string.
 *
 * @param fmt the format string used to construct a string.
 *
 * @return number of characters written, or -1 if an error occurs.
 *
 * @section syntax Format string syntax
 * The following tokens will be replaced with the specified string:
 *  \li \c \%w - This will be replaced with the name of the Watched file on
 *               which an event occurred.
 *  \li \c \%c - This will be replaced with the cookie of the Watched file on
 *               which an event occurred.
 *  \li \c \%f - When an event occurs within a directory, this will be replaced
 *               with the name of the File which caused the event to occur.
 *               Otherwise, this will be replaced with an empty string.
 *  \li \c \%e - Replaced with the Event(s) which occurred, comma-separated.
 *  \li \c \%Xe - Replaced with the Event(s) which occurred, separated by
 *                whichever character is in the place of `X'.
 *  \li \c \%T - Replaced by the current Time in the format specified by the
 *               string previously passed to inotifytools_set_printf_timefmt(),
 *               or replaced with an empty string if that function has never
 *               been called.
 *
 * @section example Example
 * @code
 * // suppose this is the only file watched.
 * inotifytools_watch_file( "mydir/", IN_CLOSE );
 *
 * // wait until an event occurs
 * struct inotify_event * event = inotifytools_next_event( -1 );
 *
 * inotifytools_fprintf(stderr, event, "in %w, file %f had event(s): %.e\n");
 * // suppose the file 'myfile' in mydir was read from and closed.  Then,
 * // this prints to standard error something like:
 * // "in mydir/, file myfile had event(s): CLOSE_NOWRITE.CLOSE.ISDIR\n"
 * @endcode
 */
int inotifytools_fprintf( FILE* file, struct inotify_event* event, char* fmt ) {
	static char out[MAX_STRLEN+1];
	static int ret;
	ret = inotifytools_sprintf( out, event, fmt );
	if ( -1 != ret ) fprintf( file, "%s", out );
	return ret;
}

/**
 * Construct a string using an inotify_event and a printf-like syntax.
 * The string can only ever be up to 4096 characters in length.
 *
 * This function will keep writing until it reaches 4096 characters.  If your
 * allocated array is not large enough to hold the entire string, your program
 * may crash.
 * inotifytools_snprintf() is safer and you should use it where possible.
 *
 * @param out location in which to store string.
 *
 * @param event the event to use to construct a string.
 *
 * @param fmt the format string used to construct a string.
 *
 * @return number of characters written, or -1 if an error occurs.
 *
 * @section syntax Format string syntax
 * The following tokens will be replaced with the specified string:
 *  \li \c \%w - This will be replaced with the name of the Watched file on
 *               which an event occurred.
 *  \li \c \%c - This will be replaced with the cookie of the Watched file on
 *               which an event occurred.
 *  \li \c \%f - When an event occurs within a directory, this will be replaced
 *               with the name of the File which caused the event to occur.
 *               Otherwise, this will be replaced with an empty string.
 *  \li \c \%e - Replaced with the Event(s) which occurred, comma-separated.
 *  \li \c \%Xe - Replaced with the Event(s) which occurred, separated by
 *                whichever character is in the place of `X'.
 *  \li \c \%T - Replaced by the current Time in the format specified by the
 *               string previously passed to inotifytools_set_printf_timefmt(),
 *               or replaced with an empty string if that function has never
 *               been called.
 *
 * @section example Example
 * @code
 * // suppose this is the only file watched.
 * inotifytools_watch_file( "mydir/", IN_CLOSE );
 *
 * // wait until an event occurs
 * struct inotify_event * event = inotifytools_next_event( -1 );
 *
 * char mystring[1024];
 * // hope this doesn't crash - if filename is really long, might not fit into
 * // mystring!
 * inotifytools_sprintf(mystring, event, "in %w, file %f had event(s): %.e\n");
 * printf( mystring );
 * // suppose the file 'myfile' in mydir was written to and closed.  Then,
 * // this prints something like:
 * // "in mydir/, file myfile had event(s): CLOSE_WRITE.CLOSE.ISDIR\n"
 * @endcode
 */
int inotifytools_sprintf( char * out, struct inotify_event* event, char* fmt ) {
	return inotifytools_snprintf( out, MAX_STRLEN, event, fmt );
}


/**
 * Construct a string using an inotify_event and a printf-like syntax.
 * The string can only ever be up to 4096 characters in length.
 *
 * @param out location in which to store string.
 *
 * @param size maximum amount of characters to write.
 *
 * @param event the event to use to construct a string.
 *
 * @param fmt the format string used to construct a string.
 *
 * @return number of characters written, or -1 if an error occurs.
 *
 * @section syntax Format string syntax
 * The following tokens will be replaced with the specified string:
 *  \li \c \%w - This will be replaced with the name of the Watched file on
 *               which an event occurred.
 *  \li \c \%c - This will be replaced with cookie of the Watched file on
 *               which an event occurred.
 *  \li \c \%f - When an event occurs within a directory, this will be replaced
 *               with the name of the File which caused the event to occur.
 *               Otherwise, this will be replaced with an empty string.
 *  \li \c \%e - Replaced with the Event(s) which occurred, comma-separated.
 *  \li \c \%Xe - Replaced with the Event(s) which occurred, separated by
 *                whichever character is in the place of `X'.
 *  \li \c \%T - Replaced by the current Time in the format specified by the
 *               string previously passed to inotifytools_set_printf_timefmt(),
 *               or replaced with an empty string if that function has never
 *               been called.
 *
 * @section example Example
 * @code
 * // suppose this is the only file watched.
 * inotifytools_watch_file( "mydir/", IN_CLOSE );
 *
 * // wait until an event occurs
 * struct inotify_event * event = inotifytools_next_event( -1 );
 *
 * char mystring[1024];
 * inotifytools_snprintf( mystring, 1024, event,
 *                        "in %w, file %f had event(s): %.e\n" );
 * printf( mystring );
 * // suppose the file 'myfile' in mydir was written to and closed.  Then,
 * // this prints something like:
 * // "in mydir/, file myfile had event(s): CLOSE_WRITE.CLOSE.ISDIR\n"
 * @endcode
 */
int inotifytools_snprintf( char * out, int size,
                           struct inotify_event* event, char* fmt ) {
	static char * filename, * eventname, * eventstr;
	static unsigned int i, ind;
	static char ch1;
	static char timestr[MAX_STRLEN];
        static time_t now;

        if ( event->len > 0 ) {
		eventname = event->name;
	}
	else {
		eventname = NULL;
	}


	filename = inotifytools_filename_from_wd( event->wd );

	if ( !fmt || 0 == strlen(fmt) ) {
		error = EINVAL;
		return -1;
	}
	if ( strlen(fmt) > MAX_STRLEN || size > MAX_STRLEN) {
		error = EMSGSIZE;
		return -1;
	}

	ind = 0;
	for ( i = 0; i < strlen(fmt) &&
	             (int)ind < size - 1; ++i ) {
		if ( fmt[i] != '%' ) {
			out[ind++] = fmt[i];
			continue;
		}

		if ( i == strlen(fmt) - 1 ) {
			// last character is %, invalid
			error = EINVAL;
			return ind;
		}

		ch1 = fmt[i+1];

		if ( ch1 == '%' ) {
			out[ind++] = '%';
			++i;
			continue;
		}

		if ( ch1 == 'w' ) {
			if ( filename ) {
				strncpy( &out[ind], filename, size - ind );
				ind += strlen(filename);
			}
			++i;
			continue;
		}

		if ( ch1 == 'f' ) {
			if ( eventname ) {
				strncpy( &out[ind], eventname, size - ind );
				ind += strlen(eventname);
			}
			++i;
			continue;
		}

		if ( ch1 == 'c' ) {
			ind += snprintf( &out[ind], size-ind, "%x", event->cookie);
			++i;
			continue;
		}

		if ( ch1 == 'e' ) {
			eventstr = inotifytools_event_to_str( event->mask );
			strncpy( &out[ind], eventstr, size - ind );
			ind += strlen(eventstr);
			++i;
			continue;
		}

		if ( ch1 == 'T' ) {

			if ( timefmt ) {
				now = time(0);
                                struct tm now_tm;
                                if (0 >= strftime(timestr, MAX_STRLEN - 1,
                                                  timefmt,
                                                  localtime_r(&now, &now_tm))) {
                                    // time format probably invalid
                                    error = EINVAL;
                                    return ind;
				}
			}
			else {
				timestr[0] = 0;
			}

			strncpy( &out[ind], timestr, size - ind );
			ind += strlen(timestr);
			++i;
			continue;
		}

		// Check if next char in fmt is e
		if ( i < strlen(fmt) - 2 && fmt[i+2] == 'e' ) {
			eventstr = inotifytools_event_to_str_sep( event->mask, ch1 );
			strncpy( &out[ind], eventstr, size - ind );
			ind += strlen(eventstr);
			i += 2;
			continue;
		}

		// OK, this wasn't a special format character, just output it as normal
		if ( ind < MAX_STRLEN ) out[ind++] = '%';
		if ( ind < MAX_STRLEN ) out[ind++] = ch1;
		++i;
	}
	out[ind] = 0;

	return ind - 1;
}

/**
 * Set time format for printf functions.
 *
 * @param fmt A format string valid for use with strftime, or NULL.  If NULL,
 *            time substitutions will no longer be made in printf functions.
 *            Note that this format string is not validated at all; using an
 *            incorrect format string will cause the printf functions to give
 *            incorrect results.
 */
void inotifytools_set_printf_timefmt( char * fmt ) {
	timefmt = fmt;
}

/**
 * Get the event queue size.
 *
 * This setting can also be read or modified by accessing the file
 * \a /proc/sys/fs/inotify/max_queued_events.
 *
 * @return the maximum number of events which will be queued in the kernel.
 */
int inotifytools_get_max_queued_events() {
	int ret;
	if ( !read_num_from_file( QUEUE_SIZE_PATH, &ret ) ) return -1;
	return ret;
}

/**
 * Get the maximum number of user instances of inotify.
 *
 * This setting can also be read or modified by accessing the file
 * \a /proc/sys/fs/inotify/max_user_instances.
 *
 * @return the maximum number of inotify file descriptors a single user can
 *         obtain.
 */
int inotifytools_get_max_user_instances() {
	int ret;
	if ( !read_num_from_file( INSTANCES_PATH, &ret ) ) return -1;
	return ret;
}

/**
 * Get the maximum number of user watches.
 *
 * This setting can also be read or modified by accessing the file
 * \a /proc/sys/fs/inotify/max_user_watches.
 *
 * @return the maximum number of inotify watches a single user can obtain per
 *         inotify instance.
 */
int inotifytools_get_max_user_watches() {
	int ret;
	if ( !read_num_from_file( WATCHES_SIZE_PATH, &ret ) ) return -1;
	return ret;
}

/**
 * Ignore inotify events matching a particular regular expression.
 *
 * @a pattern is a regular expression and @a flags is a bitwise combination of
 * POSIX regular expression flags. @a invert determines the type of filtering:
 * 0 (--exclude[i]): exclude all files matching @a pattern
 * 1 (--include[i]): exclude all files except those matching @a pattern
 *
 * On future calls to inotifytools_next_events() or inotifytools_next_event(),
 * the regular expression is executed on the filename of files on which
 * events occur.  If the regular expression matches, the matched event will be
 * ignored.
 */
static int do_ignore_events_by_regex( char const *pattern, int flags, int invert ) {
	if (!pattern) {
		if (regex) {
			regfree(regex);
			free(regex);
			regex = 0;
		}
		return 1;
	}

	if (regex) { regfree(regex); }
	else       { regex = (regex_t *)malloc(sizeof(regex_t)); }

	invert_regexp = invert;
	int ret = regcomp(regex, pattern, flags | REG_NOSUB);
	if (0 == ret) return 1;

	regfree(regex);
	free(regex);
	regex = 0;
	error = EINVAL;
	return 0;
}

/**
 * Ignore inotify events matching a particular regular expression.
 *
 * @a pattern is a regular expression and @a flags is a bitwise combination of
 * POSIX regular expression flags.
 *
 * On future calls to inotifytools_next_events() or inotifytools_next_event(),
 * the regular expression is executed on the filename of files on which
 * events occur.  If the regular expression matches, the matched event will be
 * ignored.
 */
int inotifytools_ignore_events_by_regex( char const *pattern, int flags ) {
	return do_ignore_events_by_regex(pattern, flags, 0);
}

/**
 * Ignore inotify events NOT matching a particular regular expression.
 *
 * @a pattern is a regular expression and @a flags is a bitwise combination of
 * POSIX regular expression flags.
 *
 * On future calls to inotifytools_next_events() or inotifytools_next_event(),
 * the regular expression is executed on the filename of files on which
 * events occur.  If the regular expression matches, the matched event will be
 * ignored.
 */
int inotifytools_ignore_events_by_inverted_regex( char const *pattern, int flags ) {
	return do_ignore_events_by_regex(pattern, flags, 1);
}

int event_compare(const void *p1, const void *p2, const void *config)
{
	if (!p1 || !p2) return p1 - p2;
	char asc = 1;
	long sort_event = (long)config;
	if (sort_event == -1) {
		sort_event = 0;
		asc = 0;
	} else if (sort_event < 0) {
		sort_event = -sort_event;
		asc = 0;
	}
	unsigned int *i1 = stat_ptr((watch*)p1, sort_event);
	unsigned int *i2 = stat_ptr((watch*)p2, sort_event);
	if (0 == *i1 - *i2) {
		return ((watch*)p1)->wd - ((watch*)p2)->wd;
	}
	if (asc)
		return *i1 - *i2;
	else
		return *i2 - *i1;
}

struct rbtree *inotifytools_wd_sorted_by_event(int sort_event)
{
	struct rbtree *ret = rbinit(event_compare, (void*)(uintptr_t)sort_event);
	RBLIST *all = rbopenlist(tree_wd);
	void const *p = rbreadlist(all);
	while (p) {
		void const *r = rbsearch(p, ret);
		niceassert((int)(r == p), "Couldn't insert watch into new tree");
		p = rbreadlist(all);
	}
	rbcloselist(all);
	return ret;
}