summaryrefslogtreecommitdiff
path: root/source/tools/mudraw.c
blob: 7e4b40fb7dcb939dd16a7f85426f7b44f9c27513 (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
/*
 * mudraw -- command line tool for drawing and converting documents
 */

#include "mupdf/fitz.h"
#include "mupdf/pdf.h" /* for pdf output */

#ifdef _MSC_VER
#include <winsock2.h>
#include <windows.h>
#define MUDRAW_THREADS 1
#else
#include <sys/time.h>
#ifdef HAVE_PTHREADS
#define MUDRAW_THREADS 2
#include <pthread.h>
#include <semaphore.h>
#endif
#endif

/* Enable for helpful threading debug */
/* #define DEBUG_THREADS(A) do { printf A; fflush(stdout); } while (0) */
#define DEBUG_THREADS(A) do { } while (0)

enum {
	OUT_NONE,
	OUT_PNG, OUT_TGA, OUT_PNM, OUT_PGM, OUT_PPM, OUT_PAM,
	OUT_PBM, OUT_PKM, OUT_PWG, OUT_PCL, OUT_PS,
	OUT_TEXT, OUT_HTML, OUT_STEXT,
	OUT_TRACE, OUT_SVG,
#if FZ_ENABLE_PDF
	OUT_PDF,
#endif
	OUT_GPROOF
};

enum { CS_INVALID, CS_UNSET, CS_MONO, CS_GRAY, CS_GRAY_ALPHA, CS_RGB, CS_RGB_ALPHA, CS_CMYK, CS_CMYK_ALPHA };

typedef struct
{
	char *suffix;
	int format;
} suffix_t;

static const suffix_t suffix_table[] =
{
	{ ".png", OUT_PNG },
	{ ".pgm", OUT_PGM },
	{ ".ppm", OUT_PPM },
	{ ".pnm", OUT_PNM },
	{ ".pam", OUT_PAM },
	{ ".pbm", OUT_PBM },
	{ ".pkm", OUT_PKM },
	{ ".svg", OUT_SVG },
	{ ".pwg", OUT_PWG },
	{ ".pcl", OUT_PCL },
	{ ".ps", OUT_PS },
#if FZ_ENABLE_PDF
	{ ".pdf", OUT_PDF },
#endif
	{ ".tga", OUT_TGA },

	{ ".txt", OUT_TEXT },
	{ ".text", OUT_TEXT },
	{ ".html", OUT_HTML },
	{ ".stext", OUT_STEXT },

	{ ".trace", OUT_TRACE },
	{ ".gproof", OUT_GPROOF },
};

typedef struct
{
	char *name;
	int colorspace;
} cs_name_t;

static const cs_name_t cs_name_table[] =
{
	{ "m", CS_MONO },
	{ "mono", CS_MONO },
	{ "g", CS_GRAY },
	{ "gray", CS_GRAY },
	{ "grey", CS_GRAY },
	{ "ga", CS_GRAY_ALPHA },
	{ "grayalpha", CS_GRAY_ALPHA },
	{ "greyalpha", CS_GRAY_ALPHA },
	{ "rgb", CS_RGB },
	{ "rgba", CS_RGB_ALPHA },
	{ "rgbalpha", CS_RGB_ALPHA },
	{ "cmyk", CS_CMYK },
	{ "cmyka", CS_CMYK_ALPHA },
	{ "cmykalpha", CS_CMYK_ALPHA },
};

typedef struct
{
	int format;
	int default_cs;
	int permitted_cs[6];
} format_cs_table_t;

static const format_cs_table_t format_cs_table[] =
{
	{ OUT_PNG, CS_RGB, { CS_GRAY, CS_GRAY_ALPHA, CS_RGB, CS_RGB_ALPHA } },
	{ OUT_PPM, CS_RGB, { CS_GRAY, CS_RGB } },
	{ OUT_PNM, CS_GRAY, { CS_GRAY, CS_RGB } },
	{ OUT_PAM, CS_RGB_ALPHA, { CS_GRAY, CS_GRAY_ALPHA, CS_RGB, CS_RGB_ALPHA, CS_CMYK, CS_CMYK_ALPHA } },
	{ OUT_PGM, CS_GRAY, { CS_GRAY, CS_RGB } },
	{ OUT_PBM, CS_MONO, { CS_MONO } },
	{ OUT_PKM, CS_CMYK, { CS_CMYK } },
	{ OUT_PWG, CS_RGB, { CS_MONO, CS_GRAY, CS_RGB, CS_CMYK } },
	{ OUT_PCL, CS_MONO, { CS_MONO, CS_RGB } },
	{ OUT_PS, CS_RGB, { CS_GRAY, CS_RGB, CS_CMYK } },
	{ OUT_TGA, CS_RGB, { CS_GRAY, CS_GRAY_ALPHA, CS_RGB, CS_RGB_ALPHA } },

	{ OUT_TRACE, CS_RGB, { CS_RGB } },
	{ OUT_SVG, CS_RGB, { CS_RGB } },
#if FZ_ENABLE_PDF
	{ OUT_PDF, CS_RGB, { CS_RGB } },
#endif
	{ OUT_GPROOF, CS_RGB, { CS_RGB } },

	{ OUT_TEXT, CS_RGB, { CS_RGB } },
	{ OUT_HTML, CS_RGB, { CS_RGB } },
	{ OUT_STEXT, CS_RGB, { CS_RGB } },
};

/*
	In the presence of pthreads or Windows threads, we can offer
	a multi-threaded option. In the absence, of such, we degrade
	nicely.
*/
#ifdef MUDRAW_THREADS
#if MUDRAW_THREADS == 1

/* Windows threads */
#define SEMAPHORE HANDLE
#define SEMAPHORE_INIT(A) do { A = CreateSemaphore(NULL, 0, 1, NULL); } while (0)
#define SEMAPHORE_FIN(A) do { CloseHandle(A); } while (0)
#define SEMAPHORE_TRIGGER(A) do { (void)ReleaseSemaphore(A, 1, NULL); } while (0)
#define SEMAPHORE_WAIT(A) do { (void)WaitForSingleObject(A, INFINITE); } while (0)
#define THREAD HANDLE
#define THREAD_INIT(A,B,C) do { A = CreateThread(NULL, 0, B, C, 0, NULL); } while (0)
#define THREAD_FIN(A) do { CloseHandle(A); } while (0)
#define THREAD_RETURN_TYPE DWORD WINAPI
#define THREAD_RETURN() return 0
#define MUTEX CRITICAL_SECTION
#define MUTEX_INIT(A) do { InitializeCriticalSection(&A); } while (0)
#define MUTEX_FIN(A) do { DeleteCriticalSection(&A); } while (0)
#define MUTEX_LOCK(A) do { EnterCriticalSection(&A); } while (0)
#define MUTEX_UNLOCK(A) do { LeaveCriticalSection(&A); } while (0)

#elif MUDRAW_THREADS == 2

/*
	PThreads - without working unnamed semaphores.

	Neither ios nor OSX supports unnamed semaphores.
	Named semaphores are a pain to use, so we implement
	our own semaphores using condition variables and
	mutexes.
*/

typedef struct
{
	int count;
	pthread_mutex_t mutex;
	pthread_cond_t cond;
} my_semaphore_t;

int
my_semaphore_open(my_semaphore_t *sem)
{
	int scode;

	sem->count = 0;
	scode = pthread_mutex_init(&sem->mutex, NULL);
	if (scode == 0)
	{
		scode = pthread_cond_init(&sem->cond, NULL);
		if (scode)
			pthread_mutex_destroy(&sem->mutex);
	}
	if (scode)
		memset(sem, 0, sizeof(*sem));
	return scode;
}

int
my_semaphore_close(my_semaphore_t *sem)
{
	int scode, scode2;

	scode = pthread_cond_destroy(&sem->cond);
	scode2 = pthread_mutex_destroy(&sem->mutex);
	if (scode == 0)
		scode = scode2;
	return scode;
}

int
my_semaphore_wait(my_semaphore_t *sem)
{
	int scode, scode2;

	scode = pthread_mutex_lock(&sem->mutex);
	if (scode)
		return scode;
	while (sem->count == 0) {
		scode = pthread_cond_wait(&sem->cond, &sem->mutex);
		if (scode)
			break;
	}
	if (scode == 0)
		--sem->count;
	scode2 = pthread_mutex_unlock(&sem->mutex);
	if (scode == 0)
		scode = scode2;
	return scode;
}

int
my_semaphore_signal(my_semaphore_t * sem)
{
	int scode, scode2;

	scode = pthread_mutex_lock(&sem->mutex);
	if (scode)
		return scode;
	if (sem->count++ == 0)
		scode = pthread_cond_signal(&sem->cond);
	scode2 = pthread_mutex_unlock(&sem->mutex);
	if (scode == 0)
		scode = scode2;
	return scode;
}

#define SEMAPHORE my_semaphore_t
#define SEMAPHORE_INIT(A) do { (void)my_semaphore_open(&A); } while (0)
#define SEMAPHORE_FIN(A) do { (void)my_semaphore_close(&A); } while (0)
#define SEMAPHORE_TRIGGER(A) do { (void)my_semaphore_signal(&A); } while (0)
#define SEMAPHORE_WAIT(A) do { (void)my_semaphore_wait(&A); } while (0)
#define THREAD pthread_t
#define THREAD_INIT(A,B,C) do { (void)pthread_create(&A, NULL, B, C); } while (0)
#define THREAD_FIN(A) do { void *res; (void)pthread_join(A, &res); } while (0)
#define THREAD_RETURN_TYPE void *
#define THREAD_RETURN() return NULL
#define MUTEX pthread_mutex_t
#define MUTEX_INIT(A) do { (void)pthread_mutex_init(&A, NULL); } while (0)
#define MUTEX_FIN(A) do { (void)pthread_mutex_destroy(&A); } while (0)
#define MUTEX_LOCK(A) do { (void)pthread_mutex_lock(&A); } while (0)
#define MUTEX_UNLOCK(A) do { (void)pthread_mutex_unlock(&A); } while (0)

#else
#error Unknown MUDRAW_THREADS setting
#endif

#define LOCKS_INIT() init_mudraw_locks()
#define LOCKS_FIN() fin_mudraw_locks()

static MUTEX mutexes[FZ_LOCK_MAX];

static void mudraw_lock(void *user, int lock)
{
	MUTEX_LOCK(mutexes[lock]);
}

static void mudraw_unlock(void *user, int lock)
{
	MUTEX_UNLOCK(mutexes[lock]);
}

static fz_locks_context mudraw_locks =
{
	NULL, mudraw_lock, mudraw_unlock
};

static fz_locks_context *init_mudraw_locks(void)
{
	int i;

	for (i = 0; i < FZ_LOCK_MAX; i++)
		MUTEX_INIT(mutexes[i]);

	return &mudraw_locks;
}

static void fin_mudraw_locks(void)
{
	int i;

	for (i = 0; i < FZ_LOCK_MAX; i++)
		MUTEX_FIN(mutexes[i]);
}

#else

/* Null Threads implementation */
#define SEMAPHORE int
#define THREAD int
#define SEMAPHORE_INIT(A) do { A = 0; } while (0)
#define SEMAPHORE_FIN(A) do { A = 0; } while (0)
#define SEMAPHORE_TRIGGER(A) do { A = 0; } while (0)
#define SEMAPHORE_WAIT(A) do { A = 0; } while (0)
#define THREAD_INIT(A,B,C) do { A = 0; (void)C; } while (0)
#define THREAD_FIN(A) do { A = 0; } while (0)
#define LOCKS_INIT() NULL
#define LOCKS_FIN() do { } while (0)

#endif

typedef struct worker_t {
	fz_context *ctx;
	int num;
	int band; /* -1 to shutdown, or band to render */
	fz_display_list *list;
	fz_matrix ctm;
	fz_rect tbounds;
	fz_pixmap *pix;
	fz_bitmap *bit;
	fz_cookie cookie;
	SEMAPHORE start;
	SEMAPHORE stop;
	THREAD thread;
} worker_t;

static char *output = NULL;
fz_output *out = NULL;
static int output_pagenum = 0;
static int output_append = 0;
static int output_file_per_page = 0;

static char *format = NULL;
static int output_format = OUT_NONE;

static float rotation = 0;
static float resolution = 72;
static int res_specified = 0;
static int width = 0;
static int height = 0;
static int fit = 0;

static float layout_w = 450;
static float layout_h = 600;
static float layout_em = 12;
static char *layout_css = NULL;

static int showfeatures = 0;
static int showtime = 0;
static size_t memtrace_current = 0;
static size_t memtrace_peak = 0;
static size_t memtrace_total = 0;
static int showmemory = 0;
static int showmd5 = 0;

#if FZ_ENABLE_PDF
static pdf_document *pdfout = NULL;
#endif

static int ignore_errors = 0;
static int uselist = 1;
static int alphabits_text = 8;
static int alphabits_graphics = 8;

static int out_cs = CS_UNSET;
static float gamma_value = 1;
static int invert = 0;
static int bandheight = 0;
static int lowmemory = 0;

static int errored = 0;
static fz_stext_sheet *sheet = NULL;
static fz_colorspace *colorspace;
static int alpha;
static char *filename;
static int files = 0;
static int num_workers = 0;
static worker_t *workers;

static struct {
	int active;
	int started;
	fz_context *ctx;
	THREAD thread;
	SEMAPHORE start;
	SEMAPHORE stop;
	int pagenum;
	char *filename;
	fz_display_list *list;
	fz_page *page;
	int interptime;
} bgprint;

static struct {
	int count, total;
	int min, max;
	int mininterp, maxinterp;
	int minpage, maxpage;
	char *minfilename;
	char *maxfilename;
} timing;

static void usage(void)
{
	fprintf(stderr,
		"mudraw version " FZ_VERSION "\n"
		"Usage: mudraw [options] file [pages]\n"
		"\t-p -\tpassword\n"
		"\n"
		"\t-o -\toutput file name (%%d for page number)\n"
		"\t-F -\toutput format (default inferred from output file name)\n"
		"\t\traster: png, tga, pnm, pam, pbm, pkm, pwg, pcl, ps\n"
		"\t\tvector: svg, pdf, trace\n"
		"\t\ttext: txt, html, stext\n"
		"\n"
		"\t-s -\tshow extra information:\n"
		"\t\tm - show memory use\n"
		"\t\tt - show timings\n"
		"\t\tf - show page features\n"
		"\t\t5 - show md5 checksum of rendered image\n"
		"\n"
		"\t-R -\trotate clockwise (default: 0 degrees)\n"
		"\t-r -\tresolution in dpi (default: 72)\n"
		"\t-w -\twidth (in pixels) (maximum width if -r is specified)\n"
		"\t-h -\theight (in pixels) (maximum height if -r is specified)\n"
		"\t-f -\tfit width and/or height exactly; ignore original aspect ratio\n"
		"\t-B -\tmaximum bandheight (pgm, ppm, pam, png output only)\n"
#ifdef MUDRAW_THREADS
		"\t-T -\tnumber of threads to use for rendering (banded mode only)\n"
#endif
		"\n"
		"\t-W -\tpage width for EPUB layout\n"
		"\t-H -\tpage height for EPUB layout\n"
		"\t-S -\tfont size for EPUB layout\n"
		"\t-U -\tfile name of user stylesheet for EPUB layout\n"
		"\n"
		"\t-c -\tcolorspace (mono, gray, grayalpha, rgb, rgba, cmyk, cmykalpha)\n"
		"\t-G -\tapply gamma correction\n"
		"\t-I\tinvert colors\n"
		"\n"
		"\t-A -\tnumber of bits of antialiasing (0 to 8)\n"
		"\t-A -/-\tnumber of bits of antialiasing (0 to 8) (graphics, text)\n"
		"\t-D\tdisable use of display list\n"
		"\t-i\tignore errors\n"
		"\t-L\tlow memory mode (avoid caching, clear objects after each page)\n"
		"\t-P\tparallel interpretation/rendering\n"
		"\n"
		"\tpages\tcomma separated list of page numbers and ranges\n"
		);
	exit(1);
}

static int gettime(void)
{
	static struct timeval first;
	static int once = 1;
	struct timeval now;
	if (once)
	{
		gettimeofday(&first, NULL);
		once = 0;
	}
	gettimeofday(&now, NULL);
	return (now.tv_sec - first.tv_sec) * 1000 + (now.tv_usec - first.tv_usec) / 1000;
}

static int has_percent_d(char *s)
{
	/* find '%[0-9]*d' */
	while (*s)
	{
		if (*s++ == '%')
		{
			while (*s >= '0' && *s <= '9')
				++s;
			if (*s == 'd')
				return 1;
		}
	}
	return 0;
}

/* Output file level (as opposed to page level) headers */
static void
file_level_headers(fz_context *ctx)
{
	if (output_format == OUT_STEXT || output_format == OUT_TRACE)
		fz_printf(ctx, out, "<?xml version=\"1.0\"?>\n");

	if (output_format == OUT_TEXT || output_format == OUT_HTML || output_format == OUT_STEXT)
		sheet = fz_new_stext_sheet(ctx);

	if (output_format == OUT_HTML)
	{
		fz_printf(ctx, out, "<style>\n");
		fz_printf(ctx, out, "body{background-color:gray;margin:12pt;}\n");
		fz_printf(ctx, out, "div.page{background-color:white;margin:6pt;padding:6pt;}\n");
		fz_printf(ctx, out, "div.block{border:1px solid gray;margin:6pt;padding:6pt;}\n");
		fz_printf(ctx, out, "div.metaline{display:table;width:100%%}\n");
		fz_printf(ctx, out, "div.line{display:table-row;padding:6pt}\n");
		fz_printf(ctx, out, "div.cell{display:table-cell;padding-left:6pt;padding-right:6pt}\n");
		fz_printf(ctx, out, "p{margin:0pt;padding:0pt;}\n");
		fz_printf(ctx, out, "</style>\n");
		fz_printf(ctx, out, "<body>\n");
	}

	if (output_format == OUT_STEXT || output_format == OUT_TRACE)
		fz_printf(ctx, out, "<document name=\"%s\">\n", filename);

	if (output_format == OUT_PS)
		fz_write_ps_file_header(ctx, out);
}

static void
file_level_trailers(fz_context *ctx)
{
	if (output_format == OUT_STEXT || output_format == OUT_TRACE)
		fz_printf(ctx, out, "</document>\n");

	if (output_format == OUT_HTML)
	{
		fz_printf(ctx, out, "</body>\n");
		fz_printf(ctx, out, "<style>\n");
		fz_print_stext_sheet(ctx, out, sheet);
		fz_printf(ctx, out, "</style>\n");
	}

	if (output_format == OUT_PS)
		fz_write_ps_file_trailer(ctx, out, output_pagenum);

	fz_drop_stext_sheet(ctx, sheet);
}

static void drawband(fz_context *ctx, fz_page *page, fz_display_list *list, const fz_matrix *ctm, const fz_rect *tbounds, fz_cookie *cookie, int band_start, fz_pixmap *pix, fz_bitmap **bit)
{
	fz_device *dev = NULL;

	*bit = NULL;

	fz_try(ctx)
	{
		if (pix->alpha)
			fz_clear_pixmap(ctx, pix);
		else
			fz_clear_pixmap_with_value(ctx, pix, 255);

		dev = fz_new_draw_device(ctx, ctm, pix);
		if (lowmemory)
			fz_enable_device_hints(ctx, dev, FZ_NO_CACHE);
		if (alphabits_graphics == 0)
			fz_enable_device_hints(ctx, dev, FZ_DONT_INTERPOLATE_IMAGES);
		if (list)
			fz_run_display_list(ctx, list, dev, &fz_identity, tbounds, cookie);
		else
			fz_run_page(ctx, page, dev, &fz_identity, cookie);
		fz_drop_device(ctx, dev);
		dev = NULL;

		if (invert)
			fz_invert_pixmap(ctx, pix);
		if (gamma_value != 1)
			fz_gamma_pixmap(ctx, pix, gamma_value);

		if (pix->alpha)
			fz_unmultiply_pixmap(ctx, pix);

		if ((output_format == OUT_PCL && out_cs == CS_MONO) || (output_format == OUT_PBM) || (output_format == OUT_PKM))
			*bit = fz_new_bitmap_from_pixmap_band(ctx, pix, NULL, band_start, bandheight);
	}
	fz_catch(ctx)
	{
		fz_drop_device(ctx, dev);
		fz_rethrow(ctx);
	}
}

static void dodrawpage(fz_context *ctx, fz_page *page, fz_display_list *list, int pagenum, fz_cookie *cookie, int start, int interptime, char *filename, int bg)
{
	fz_rect mediabox;
	fz_device *dev = NULL;

	fz_bound_page(ctx, page, &mediabox);

	if (output_format == OUT_TRACE)
	{
		fz_try(ctx)
		{
			fz_printf(ctx, out, "<page mediabox=\"%g %g %g %g\">\n",
					mediabox.x0, mediabox.y0, mediabox.x1, mediabox.y1);
			dev = fz_new_trace_device(ctx, out);
			if (lowmemory)
				fz_enable_device_hints(ctx, dev, FZ_NO_CACHE);
			if (list)
				fz_run_display_list(ctx, list, dev, &fz_identity, &fz_infinite_rect, cookie);
			else
				fz_run_page(ctx, page, dev, &fz_identity, cookie);
			fz_printf(ctx, out, "</page>\n");
		}
		fz_always(ctx)
		{
			fz_drop_device(ctx, dev);
			dev = NULL;
		}
		fz_catch(ctx)
		{
			fz_drop_display_list(ctx, list);
			fz_drop_page(ctx, page);
			fz_rethrow(ctx);
		}
	}

	else if (output_format == OUT_TEXT || output_format == OUT_HTML || output_format == OUT_STEXT)
	{
		fz_stext_page *text = NULL;

		fz_var(text);

		fz_try(ctx)
		{
			text = fz_new_stext_page(ctx);
			dev = fz_new_stext_device(ctx, sheet, text);
			if (lowmemory)
				fz_enable_device_hints(ctx, dev, FZ_NO_CACHE);
			if (output_format == OUT_HTML)
				fz_disable_device_hints(ctx, dev, FZ_IGNORE_IMAGE);
			if (list)
				fz_run_display_list(ctx, list, dev, &fz_identity, &fz_infinite_rect, cookie);
			else
				fz_run_page(ctx, page, dev, &fz_identity, cookie);
			fz_drop_device(ctx, dev);
			dev = NULL;
			if (output_format == OUT_STEXT)
			{
				fz_print_stext_page_xml(ctx, out, text);
			}
			else if (output_format == OUT_HTML)
			{
				fz_analyze_text(ctx, sheet, text);
				fz_print_stext_page_html(ctx, out, text);
			}
			else if (output_format == OUT_TEXT)
			{
				fz_print_stext_page(ctx, out, text);
				fz_printf(ctx, out, "\f\n");
			}
		}
		fz_always(ctx)
		{
			fz_drop_device(ctx, dev);
			dev = NULL;
			fz_drop_stext_page(ctx, text);
		}
		fz_catch(ctx)
		{
			fz_drop_display_list(ctx, list);
			fz_drop_page(ctx, page);
			fz_rethrow(ctx);
		}
	}

#if FZ_ENABLE_PDF
	else if (output_format == OUT_PDF)
	{
		fz_buffer *contents;
		pdf_obj *resources;

		dev = pdf_page_write(ctx, pdfout, &mediabox, &resources, &contents);
		fz_try(ctx)
		{
			pdf_obj *page_obj;

			if (list)
				fz_run_display_list(ctx, list, dev, &fz_identity, NULL, cookie);
			else
				fz_run_page(ctx, page, dev, &fz_identity, cookie);

			page_obj = pdf_add_page(ctx, pdfout, &mediabox, rotation, resources, contents);
			pdf_insert_page(ctx, pdfout, -1, page_obj);
			pdf_drop_obj(ctx, page_obj);
		}
		fz_always(ctx)
		{
			pdf_drop_obj(ctx, resources);
			fz_drop_buffer(ctx, contents);
			fz_drop_device(ctx, dev);
			dev = NULL;
		}
		fz_catch(ctx)
		{
			fz_drop_display_list(ctx, list);
			fz_drop_page(ctx, page);
			fz_rethrow(ctx);
		}
	}
#endif

	else if (output_format == OUT_SVG)
	{
		float zoom;
		fz_matrix ctm;
		fz_rect bounds, tbounds;
		char buf[512];
		fz_output *out;

		if (!strcmp(output, "-"))
			out = fz_stdout(ctx);
		else
		{
			sprintf(buf, output, pagenum);
			out = fz_new_output_with_path(ctx, buf, 0);
		}

		fz_bound_page(ctx, page, &bounds);
		zoom = resolution / 72;
		fz_pre_rotate(fz_scale(&ctm, zoom, zoom), rotation);
		tbounds = bounds;
		fz_transform_rect(&tbounds, &ctm);

		fz_try(ctx)
		{
			dev = fz_new_svg_device(ctx, out, tbounds.x1-tbounds.x0, tbounds.y1-tbounds.y0);
			if (lowmemory)
				fz_enable_device_hints(ctx, dev, FZ_NO_CACHE);
			if (list)
				fz_run_display_list(ctx, list, dev, &ctm, &tbounds, cookie);
			else
				fz_run_page(ctx, page, dev, &ctm, cookie);
			fz_drop_device(ctx, dev);
			dev = NULL;
		}
		fz_always(ctx)
		{
			fz_drop_device(ctx, dev);
			dev = NULL;
			fz_drop_output(ctx, out);
		}
		fz_catch(ctx)
		{
			fz_drop_display_list(ctx, list);
			fz_drop_page(ctx, page);
			fz_rethrow(ctx);
		}
	}
	else
	{
		float zoom;
		fz_matrix ctm;
		fz_rect bounds, tbounds;
		fz_irect ibounds;
		fz_pixmap *pix = NULL;
		int w, h;
		fz_png_output_context *poc = NULL;
		fz_ps_output_context *psoc = NULL;
		fz_mono_pcl_output_context *pmcoc = NULL;
		fz_color_pcl_output_context *pccoc = NULL;
		fz_device *dev = NULL;
		fz_bitmap *bit = NULL;

		fz_var(dev);
		fz_var(pix);
		fz_var(poc);
		fz_var(psoc);
		fz_var(pmcoc);
		fz_var(pccoc);
		fz_var(bit);

		fz_bound_page(ctx, page, &bounds);
		zoom = resolution / 72;
		fz_pre_scale(fz_rotate(&ctm, rotation), zoom, zoom);
		tbounds = bounds;
		fz_round_rect(&ibounds, fz_transform_rect(&tbounds, &ctm));

		/* Make local copies of our width/height */
		w = width;
		h = height;

		/* If a resolution is specified, check to see whether w/h are
		 * exceeded; if not, unset them. */
		if (res_specified)
		{
			int t;
			t = ibounds.x1 - ibounds.x0;
			if (w && t <= w)
				w = 0;
			t = ibounds.y1 - ibounds.y0;
			if (h && t <= h)
				h = 0;
		}

		/* Now w or h will be 0 unless they need to be enforced. */
		if (w || h)
		{
			float scalex = w / (tbounds.x1 - tbounds.x0);
			float scaley = h / (tbounds.y1 - tbounds.y0);
			fz_matrix scale_mat;

			if (fit)
			{
				if (w == 0)
					scalex = 1.0f;
				if (h == 0)
					scaley = 1.0f;
			}
			else
			{
				if (w == 0)
					scalex = scaley;
				if (h == 0)
					scaley = scalex;
			}
			if (!fit)
			{
				if (scalex > scaley)
					scalex = scaley;
				else
					scaley = scalex;
			}
			fz_scale(&scale_mat, scalex, scaley);
			fz_concat(&ctm, &ctm, &scale_mat);
			tbounds = bounds;
			fz_transform_rect(&tbounds, &ctm);
		}
		fz_round_rect(&ibounds, &tbounds);
		fz_rect_from_irect(&tbounds, &ibounds);

		fz_try(ctx)
		{
			fz_irect band_ibounds = ibounds;
			int band, bands = 1;
			int totalheight = ibounds.y1 - ibounds.y0;
			int drawheight = totalheight;

			if (bandheight != 0)
			{
				/* Banded rendering; we'll only render to a
				 * given height at a time. */
				drawheight = bandheight;
				if (totalheight > bandheight)
					band_ibounds.y1 = band_ibounds.y0 + bandheight;
				bands = (totalheight + bandheight-1)/bandheight;
				tbounds.y1 = tbounds.y0 + bandheight + 2;
				DEBUG_THREADS(("Using %d Bands\n", bands));
			}

			if (num_workers > 0)
			{
				for (band = 0; band < fz_mini(num_workers, bands); band++)
				{
					workers[band].band = band;
					workers[band].ctm = ctm;
					workers[band].tbounds = tbounds;
					memset(&workers[band].cookie, 0, sizeof(fz_cookie));
					workers[band].list = list;
					workers[band].pix = fz_new_pixmap_with_bbox(ctx, colorspace, &band_ibounds, alpha);
					fz_set_pixmap_resolution(ctx, workers[band].pix, resolution, resolution);
					DEBUG_THREADS(("Worker %d, Pre-triggering band %d\n", band, band));
					SEMAPHORE_TRIGGER(workers[band].start);
					ctm.f -= drawheight;
				}
				pix = workers[0].pix;
			}
			else
			{
				pix = fz_new_pixmap_with_bbox(ctx, colorspace, &band_ibounds, alpha);
				fz_set_pixmap_resolution(ctx, pix, resolution, resolution);
			}

			/* Output any page level headers (for banded formats) */
			if (output)
			{
				if (output_format == OUT_PGM || output_format == OUT_PPM || output_format == OUT_PNM)
					fz_write_pnm_header(ctx, out, pix->w, totalheight, pix->n, pix->alpha);
				else if (output_format == OUT_PAM)
					fz_write_pam_header(ctx, out, pix->w, totalheight, pix->n, pix->alpha);
				else if (output_format == OUT_PNG)
					poc = fz_write_png_header(ctx, out, pix->w, totalheight, pix->n, pix->alpha);
				else if (output_format == OUT_PBM)
					fz_write_pbm_header(ctx, out, pix->w, totalheight);
				else if (output_format == OUT_PKM)
					fz_write_pkm_header(ctx, out, pix->w, totalheight);
				else if (output_format == OUT_PS)
					psoc = fz_write_ps_header(ctx, out, pix->w, totalheight, pix->n, pix->xres, pix->yres, ++output_pagenum);
				else if (output_format == OUT_PCL)
				{
					if (out_cs == CS_MONO)
						pmcoc = fz_write_mono_pcl_header(ctx, out, pix->w, totalheight, pix->xres, pix->yres, ++output_pagenum, NULL);
					else
						pccoc = fz_write_color_pcl_header(ctx, out, pix->w, totalheight, pix->n, pix->xres, pix->yres, ++output_pagenum, NULL);
				}
			}

			for (band = 0; band < bands; band++)
			{
				if (num_workers > 0)
				{
					worker_t *w = &workers[band % num_workers];
					DEBUG_THREADS(("Waiting for worker %d to complete band %d\n", w->num, band));
					SEMAPHORE_WAIT(w->stop);
					pix = w->pix;
					bit = w->bit;
					w->bit = NULL;
					cookie->errors += w->cookie.errors;
				}
				else
					drawband(ctx, page, list, &ctm, &tbounds, cookie, band * bandheight, pix, &bit);

				if (output)
				{
					if (output_format == OUT_PGM || output_format == OUT_PPM || output_format == OUT_PNM)
						fz_write_pnm_band(ctx, out, pix->w, totalheight, pix->n, pix->alpha, pix->stride, band, drawheight, pix->samples);
					else if (output_format == OUT_PAM)
						fz_write_pam_band(ctx, out, pix->w, totalheight, pix->n, pix->alpha, pix->stride, band, drawheight, pix->samples);
					else if (output_format == OUT_PNG)
						fz_write_png_band(ctx, out, poc, pix->stride, band, drawheight, pix->samples);
					else if (output_format == OUT_PWG)
						fz_write_pixmap_as_pwg(ctx, out, pix, NULL);
					else if (output_format == OUT_PCL)
					{
						if (out_cs == CS_MONO)
						{
							fz_write_mono_pcl_band(ctx, out, pmcoc, bit);
							fz_drop_bitmap(ctx, bit);
							bit = NULL;
						}
						else
							fz_write_color_pcl_band(ctx, out, pccoc, pix->w, totalheight, pix->n, pix->stride, band, drawheight, pix->samples);
					}
					else if (output_format == OUT_PS)
						fz_write_ps_band(ctx, out, psoc, pix->w, totalheight, pix->n, pix->stride, band, drawheight, pix->samples);
					else if (output_format == OUT_PBM)
					{
						fz_write_pbm_band(ctx, out, bit);
						fz_drop_bitmap(ctx, bit);
						bit = NULL;
					}
					else if (output_format == OUT_PKM)
					{
						fz_write_pkm_band(ctx, out, bit);
						fz_drop_bitmap(ctx, bit);
						bit = NULL;
					}
					else if (output_format == OUT_TGA)
					{
						fz_write_pixmap_as_tga(ctx, out, pix);
					}
				}

				if (num_workers > 0 && band + num_workers < bands)
				{
					worker_t *w = &workers[band % num_workers];
					w->band = band + num_workers;
					w->ctm = ctm;
					w->tbounds = tbounds;
					memset(&w->cookie, 0, sizeof(fz_cookie));
					DEBUG_THREADS(("Triggering worker %d for band %d\n", w->num, w->band));
					SEMAPHORE_TRIGGER(w->start);
				}
				ctm.f -= drawheight;
			}

			/* FIXME */
			if (showmd5)
			{
				unsigned char digest[16];
				int i;

				fz_md5_pixmap(ctx, pix, digest);
				fprintf(stderr, " ");
				for (i = 0; i < 16; i++)
					fprintf(stderr, "%02x", digest[i]);
			}

			/* Any page level trailers go here */
			if (output)
			{
				if (output_format == OUT_PNG)
					fz_write_png_trailer(ctx, out, poc);
				if (output_format == OUT_PS)
					fz_write_ps_trailer(ctx, out, psoc);
				if (output_format == OUT_PCL)
				{
					if (out_cs == CS_MONO)
						fz_write_mono_pcl_trailer(ctx, out, pmcoc);
					else
						fz_write_color_pcl_trailer(ctx, out, pccoc);
				}
			}
		}
		fz_always(ctx)
		{
			fz_drop_bitmap(ctx, bit);
			bit = NULL;
			fz_drop_device(ctx, dev);
			dev = NULL;
			if (num_workers > 0)
			{
				int band;
				for (band = 0; band < num_workers; band++)
					fz_drop_pixmap(ctx, workers[band].pix);
			}
			else
				fz_drop_pixmap(ctx, pix);
		}
		fz_catch(ctx)
		{
			fz_drop_display_list(ctx, list);
			fz_drop_page(ctx, page);
			fz_rethrow(ctx);
		}
	}

	if (list)
		fz_drop_display_list(ctx, list);

	if (!output_append)
		file_level_trailers(ctx);

	fz_drop_page(ctx, page);

	if (showtime)
	{
		int end = gettime();
		int diff = end - start;

		if (bg)
		{
			if (diff + interptime < timing.min)
			{
				timing.min = diff + interptime;
				timing.mininterp = interptime;
				timing.minpage = pagenum;
				timing.minfilename = filename;
			}
			if (diff + interptime > timing.max)
			{
				timing.max = diff + interptime;
				timing.maxinterp = interptime;
				timing.maxpage = pagenum;
				timing.maxfilename = filename;
			}
			timing.count ++;

			fprintf(stderr, " %dms (interpretation) %dms (rendering) %dms (total)", interptime, diff, diff + interptime);
		}
		else
		{
			if (diff < timing.min)
			{
				timing.min = diff;
				timing.minpage = pagenum;
				timing.minfilename = filename;
			}
			if (diff > timing.max)
			{
				timing.max = diff;
				timing.maxpage = pagenum;
				timing.maxfilename = filename;
			}
			timing.total += diff;
			timing.count ++;

			fprintf(stderr, " %dms", diff);
		}
	}

	fprintf(stderr, "\n");

	if (lowmemory)
	{
		fz_empty_store(ctx);
	}

	if (showmemory)
	{
		fz_dump_glyph_cache_stats(ctx);
	}

	fz_flush_warnings(ctx);

	if (cookie->errors)
		errored = 1;
}

static void bgprint_flush(void)
{
	if (!bgprint.active || !bgprint.started)
		return;

	SEMAPHORE_WAIT(bgprint.stop);
	bgprint.started = 0;
}

static void drawpage(fz_context *ctx, fz_document *doc, int pagenum)
{
	fz_page *page;
	fz_display_list *list = NULL;
	fz_device *dev = NULL;
	int start;
	fz_cookie cookie = { 0 };
	int first_page = !output_append;
	fz_rect bounds;

	fz_var(list);
	fz_var(dev);

	start = (showtime ? gettime() : 0);

	page = fz_load_page(ctx, doc, pagenum - 1);

	/* Output any file level (as opposed to page level) headers. */
	if (first_page)
		file_level_headers(ctx);

	if (uselist)
	{
		fz_try(ctx)
		{
			list = fz_new_display_list(ctx, fz_bound_page(ctx, page, &bounds));
			dev = fz_new_list_device(ctx, list);
			if (lowmemory)
				fz_enable_device_hints(ctx, dev, FZ_NO_CACHE);
			fz_run_page(ctx, page, dev, &fz_identity, &cookie);
		}
		fz_always(ctx)
		{
			fz_drop_device(ctx, dev);
			dev = NULL;
		}
		fz_catch(ctx)
		{
			fz_drop_display_list(ctx, list);
			fz_drop_page(ctx, page);
			fz_rethrow(ctx);
		}

		if (bgprint.active && showtime)
		{
			int end = gettime();
			start = end - start;
		}
	}

	if (showfeatures)
	{
		int iscolor;
		dev = fz_new_test_device(ctx, &iscolor, 0.02f, 0, NULL);
		if (lowmemory)
			fz_enable_device_hints(ctx, dev, FZ_NO_CACHE);
		fz_try(ctx)
		{
			if (list)
				fz_run_display_list(ctx, list, dev, &fz_identity, &fz_infinite_rect, NULL);
			else
				fz_run_page(ctx, page, dev, &fz_identity, &cookie);
		}
		fz_always(ctx)
		{
			fz_drop_device(ctx, dev);
			dev = NULL;
		}
		fz_catch(ctx)
		{
			fz_rethrow(ctx);
		}
		fprintf(stderr, " %s", iscolor ? "color" : "grayscale");
	}

	if (output_file_per_page)
	{
		char text_buffer[512];

		bgprint_flush();
		fz_drop_output(ctx, out);
		fz_snprintf(text_buffer, sizeof(text_buffer), output, pagenum);
		out = fz_new_output_with_path(ctx, text_buffer, output_append);
		output_append = 1;
	}

	if (bgprint.active)
	{
		bgprint_flush();
		if (bgprint.active)
		{
			fprintf(stderr, "page %s %d", filename, pagenum);
		}

		bgprint.started = 1;
		bgprint.page = page;
		bgprint.list = list;
		bgprint.filename = filename;
		bgprint.pagenum = pagenum;
		bgprint.interptime = start;
		SEMAPHORE_TRIGGER(bgprint.start);
	}
	else
	{
		fprintf(stderr, "page %s %d%s", filename, pagenum, showmd5 || showtime || showfeatures ? "" : "\n");
		dodrawpage(ctx, page, list, pagenum, &cookie, start, 0, filename, 0);
	}
}

static void drawrange(fz_context *ctx, fz_document *doc, const char *range)
{
	int page, spage, epage, pagecount;

	pagecount = fz_count_pages(ctx, doc);

	while ((range = fz_parse_page_range(ctx, range, &spage, &epage, pagecount)))
	{
		if (spage < epage)
			for (page = spage; page <= epage; page++)
				drawpage(ctx, doc, page);
		else
			for (page = spage; page >= epage; page--)
				drawpage(ctx, doc, page);
	}
}

static int
parse_colorspace(const char *name)
{
	int i;

	for (i = 0; i < nelem(cs_name_table); i++)
	{
		if (!strcmp(name, cs_name_table[i].name))
			return cs_name_table[i].colorspace;
	}
	fprintf(stderr, "Unknown colorspace \"%s\"\n", name);
	exit(1);
}

typedef struct
{
	size_t size;
#if defined(_M_IA64) || defined(_M_AMD64)
	size_t align;
#endif
} trace_header;

static void *
trace_malloc(void *arg, size_t size)
{
	trace_header *p;
	if (size == 0)
		return NULL;
	p = malloc(size + sizeof(trace_header));
	if (p == NULL)
		return NULL;
	p[0].size = size;
	memtrace_current += size;
	memtrace_total += size;
	if (memtrace_current > memtrace_peak)
		memtrace_peak = memtrace_current;
	return (void *)&p[1];
}

static void
trace_free(void *arg, void *p_)
{
	trace_header *p = (trace_header *)p_;

	if (p == NULL)
		return;
	memtrace_current -= p[-1].size;
	free(&p[-1]);
}

static void *
trace_realloc(void *arg, void *p_, size_t size)
{
	trace_header *p = (trace_header *)p_;
	size_t oldsize;

	if (size == 0)
	{
		trace_free(arg, p_);
		return NULL;
	}
	if (p == NULL)
		return trace_malloc(arg, size);
	oldsize = p[-1].size;
	p = realloc(&p[-1], size + sizeof(trace_header));
	if (p == NULL)
		return NULL;
	memtrace_current += size - oldsize;
	if (size > oldsize)
		memtrace_total += size - oldsize;
	if (memtrace_current > memtrace_peak)
		memtrace_peak = memtrace_current;
	p[0].size = size;
	return &p[1];
}

#ifdef MUDRAW_THREADS
static THREAD_RETURN_TYPE worker_thread(void *arg)
{
	worker_t *me = (worker_t *)arg;

	do
	{
		DEBUG_THREADS(("Worker %d waiting\n", me->num));
		SEMAPHORE_WAIT(me->start);
		DEBUG_THREADS(("Worker %d woken for band %d\n", me->num, me->band));
		if (me->band >= 0)
			drawband(me->ctx, NULL, me->list, &me->ctm, &me->tbounds, &me->cookie, me->band * bandheight, me->pix, &me->bit);
		DEBUG_THREADS(("Worker %d completed band %d\n", me->num, me->band));
		SEMAPHORE_TRIGGER(me->stop);
	}
	while (me->band >= 0);
	THREAD_RETURN();
}

static THREAD_RETURN_TYPE bgprint_worker(void *arg)
{
	fz_cookie cookie = { 0 };
	int pagenum;

	(void)arg;

	do
	{
		DEBUG_THREADS(("BGPrint waiting\n"));
		SEMAPHORE_WAIT(bgprint.start);
		pagenum = bgprint.pagenum;
		DEBUG_THREADS(("BGPrint woken for pagenum %d\n", pagenum));
		if (pagenum >= 0)
		{
			int start = gettime();
			memset(&cookie, 0, sizeof(cookie));
			dodrawpage(bgprint.ctx, bgprint.page, bgprint.list, pagenum, &cookie, start, bgprint.interptime, bgprint.filename, 1);
		}
		DEBUG_THREADS(("BGPrint completed page %d\n", pagenum));
		SEMAPHORE_TRIGGER(bgprint.stop);
	}
	while (pagenum >= 0);
	THREAD_RETURN();
}
#endif

#ifdef MUDRAW_STANDALONE
int main(int argc, char **argv)
#else
int mudraw_main(int argc, char **argv)
#endif
{
	char *password = "";
	fz_document *doc = NULL;
	int c, i;
	fz_context *ctx;
	fz_alloc_context alloc_ctx = { NULL, trace_malloc, trace_realloc, trace_free };

	fz_var(doc);

	while ((c = fz_getopt(argc, argv, "p:o:F:R:r:w:h:fB:c:G:Is:A:DiW:H:S:T:U:LvP")) != -1)
	{
		switch (c)
		{
		default: usage(); break;

		case 'p': password = fz_optarg; break;

		case 'o': output = fz_optarg; break;
		case 'F': format = fz_optarg; break;

		case 'R': rotation = atof(fz_optarg); break;
		case 'r': resolution = atof(fz_optarg); res_specified = 1; break;
		case 'w': width = atof(fz_optarg); break;
		case 'h': height = atof(fz_optarg); break;
		case 'f': fit = 1; break;
		case 'B': bandheight = atoi(fz_optarg); break;

		case 'c': out_cs = parse_colorspace(fz_optarg); break;
		case 'G': gamma_value = atof(fz_optarg); break;
		case 'I': invert++; break;

		case 'W': layout_w = atof(fz_optarg); break;
		case 'H': layout_h = atof(fz_optarg); break;
		case 'S': layout_em = atof(fz_optarg); break;
		case 'U': layout_css = fz_optarg; break;

		case 's':
			if (strchr(fz_optarg, 't')) ++showtime;
			if (strchr(fz_optarg, 'm')) ++showmemory;
			if (strchr(fz_optarg, 'f')) ++showfeatures;
			if (strchr(fz_optarg, '5')) ++showmd5;
			break;

		case 'A':
		{
			char *sep;
			alphabits_graphics = atoi(fz_optarg);
			sep = strchr(fz_optarg, '/');
			if (sep)
				alphabits_text = atoi(sep+1);
			else
				alphabits_text = alphabits_graphics;
			break;
		}
		case 'D': uselist = 0; break;
		case 'i': ignore_errors = 1; break;

		case 'T':
#ifdef MUDRAW_THREADS
			num_workers = atoi(fz_optarg); break;
#else
			fprintf(stderr, "Threads not enabled in this build\n");
			break;
#endif
		case 'L': lowmemory = 1; break;
		case 'P': bgprint.active = 1; break;

		case 'v': fprintf(stderr, "mudraw version %s\n", FZ_VERSION); return 1;
		}
	}

	if (fz_optind == argc)
		usage();

	if (num_workers > 0)
	{
		if (uselist == 0)
		{
			fprintf(stderr, "cannot use multiple threads without using display list\n");
			exit(1);
		}

		if (bandheight == 0)
		{
			fprintf(stderr, "Using multiple threads without banding is pointless\n");
		}
	}

	if (bgprint.active)
	{
		if (uselist == 0)
		{
			fprintf(stderr, "cannot bgprint without using display list\n");
			exit(1);
		}
	}

	ctx = fz_new_context((showmemory == 0 ? NULL : &alloc_ctx), LOCKS_INIT(), (lowmemory ? 1 : FZ_STORE_DEFAULT));
	if (!ctx)
	{
		fprintf(stderr, "cannot initialise context\n");
		exit(1);
	}

	fz_set_text_aa_level(ctx, alphabits_text);
	fz_set_graphics_aa_level(ctx, alphabits_graphics);

	if (bgprint.active)
	{
		bgprint.ctx = fz_clone_context(ctx);
		SEMAPHORE_INIT(bgprint.start);
		SEMAPHORE_INIT(bgprint.stop);
		THREAD_INIT(bgprint.thread, bgprint_worker, NULL);
	}

	if (num_workers > 0)
	{
		workers = fz_calloc(ctx, num_workers, sizeof(*workers));
		for (i = 0; i < num_workers; i++)
		{
			workers[i].ctx = fz_clone_context(ctx);
			workers[i].num = i;
			SEMAPHORE_INIT(workers[i].start);
			SEMAPHORE_INIT(workers[i].stop);
			THREAD_INIT(workers[i].thread, worker_thread, &workers[i]);
		}
	}

	if (layout_css)
	{
		fz_buffer *buf = fz_read_file(ctx, layout_css);
		fz_write_buffer_byte(ctx, buf, 0);
		fz_set_user_css(ctx, (char*)buf->data);
		fz_drop_buffer(ctx, buf);
	}

	/* Determine output type */
	if (bandheight < 0)
	{
		fprintf(stderr, "Bandheight must be > 0\n");
		exit(1);
	}

	output_format = OUT_PNG;
	if (format)
	{
		int i;

		for (i = 0; i < nelem(suffix_table); i++)
		{
			if (!strcmp(format, suffix_table[i].suffix+1))
			{
				output_format = suffix_table[i].format;
				break;
			}
		}
		if (i == nelem(suffix_table))
		{
			fprintf(stderr, "Unknown output format '%s'\n", format);
			exit(1);
		}
	}
	else if (output)
	{
		char *suffix = output;
		int i;

		for (i = 0; i < nelem(suffix_table); i++)
		{
			char *s = strstr(suffix, suffix_table[i].suffix);

			if (s != NULL)
			{
				suffix = s+1;
				output_format = suffix_table[i].format;
				i = 0;
			}
		}
	}

	if (bandheight)
	{
		if (output_format != OUT_PAM && output_format != OUT_PGM && output_format != OUT_PPM && output_format != OUT_PNM && output_format != OUT_PNG && output_format != OUT_PBM && output_format != OUT_PKM && output_format != OUT_PCL && output_format != OUT_PS)
		{
			fprintf(stderr, "Banded operation only possible with PAM, PBM, PGM, PKM, PPM, PNM, PCL, PS and PNG outputs\n");
			exit(1);
		}
		if (showmd5)
		{
			fprintf(stderr, "Banded operation not compatible with MD5\n");
			exit(1);
		}
	}

	{
		int i, j;

		for (i = 0; i < nelem(format_cs_table); i++)
		{
			if (format_cs_table[i].format == output_format)
			{
				if (out_cs == CS_UNSET)
					out_cs = format_cs_table[i].default_cs;
				for (j = 0; j < nelem(format_cs_table[i].permitted_cs); j++)
				{
					if (format_cs_table[i].permitted_cs[j] == out_cs)
						break;
				}
				if (j == nelem(format_cs_table[i].permitted_cs))
				{
					fprintf(stderr, "Unsupported colorspace for this format\n");
					exit(1);
				}
			}
		}
	}

	alpha = 1;
	switch (out_cs)
	{
	case CS_MONO:
	case CS_GRAY:
	case CS_GRAY_ALPHA:
		colorspace = fz_device_gray(ctx);
		alpha = (out_cs == CS_GRAY_ALPHA);
		break;
	case CS_RGB:
	case CS_RGB_ALPHA:
		colorspace = fz_device_rgb(ctx);
		alpha = (out_cs == CS_RGB_ALPHA);
		break;
	case CS_CMYK:
	case CS_CMYK_ALPHA:
		colorspace = fz_device_cmyk(ctx);
		alpha = (out_cs == CS_CMYK_ALPHA);
		break;
	default:
		fprintf(stderr, "Unknown colorspace!\n");
		exit(1);
		break;
	}

#if FZ_ENABLE_PDF
	if (output_format == OUT_PDF)
	{
		pdfout = pdf_create_document(ctx);
	}
	else
#endif
	if (output_format == OUT_GPROOF)
	{
		/* GPROOF files are saved direct. Do not open "output". */
	}
	else if (output && (output[0] != '-' || output[1] != 0) && *output != 0)
	{
		if (has_percent_d(output))
			output_file_per_page = 1;
		else
			out = fz_new_output_with_path(ctx, output, 0);
	}
	else
		out = fz_stdout(ctx);

	timing.count = 0;
	timing.total = 0;
	timing.min = 1 << 30;
	timing.max = 0;
	timing.mininterp = 1 << 30;
	timing.maxinterp = 0;
	timing.minpage = 0;
	timing.maxpage = 0;
	timing.minfilename = "";
	timing.maxfilename = "";
	if (showtime && bgprint.active)
		timing.total = gettime();

	fz_try(ctx)
	{
		fz_register_document_handlers(ctx);

		while (fz_optind < argc)
		{
			fz_try(ctx)
			{
				filename = argv[fz_optind++];
				files++;

				doc = fz_open_document(ctx, filename);

				if (fz_needs_password(ctx, doc))
				{
					if (!fz_authenticate_password(ctx, doc, password))
						fz_throw(ctx, FZ_ERROR_GENERIC, "cannot authenticate password: %s", filename);
				}

				fz_layout_document(ctx, doc, layout_w, layout_h, layout_em);

				if (output_format == OUT_GPROOF)
				{
					fz_save_gproof(ctx, filename, doc, output, resolution, "", "");
				}
				else
				{
					if (fz_optind == argc || !fz_is_page_range(ctx, argv[fz_optind]))
						drawrange(ctx, doc, "1-N");
					if (fz_optind < argc && fz_is_page_range(ctx, argv[fz_optind]))
						drawrange(ctx, doc, argv[fz_optind++]);
				}

				bgprint_flush();
				fz_drop_document(ctx, doc);
				doc = NULL;
			}
			fz_catch(ctx)
			{
				if (!ignore_errors)
					fz_rethrow(ctx);

				bgprint_flush();
				fz_drop_document(ctx, doc);
				doc = NULL;
				fz_warn(ctx, "ignoring error in '%s'", filename);
			}
		}
	}
	fz_catch(ctx)
	{
		bgprint_flush();
		fz_drop_document(ctx, doc);
		fprintf(stderr, "error: cannot draw '%s'\n", filename);
		errored = 1;
	}

	if (output_append)
		file_level_trailers(ctx);

#if FZ_ENABLE_PDF
	if (output_format == OUT_PDF)
	{
		if (!output)
			output = "out.pdf";
		pdf_save_document(ctx, pdfout, output, NULL);
		pdf_drop_document(ctx, pdfout);
	}
	else
#endif
	if (output_format == OUT_GPROOF)
	{
		/* No output file to close */
	}
	else
	{
		fz_drop_output(ctx, out);
		out = NULL;
	}

	if (showtime && timing.count > 0)
	{
		if (bgprint.active)
			timing.total = gettime() - timing.total;

		if (files == 1)
		{
			fprintf(stderr, "total %dms / %d pages for an average of %dms\n",
				timing.total, timing.count, timing.total / timing.count);
			if (bgprint.active)
			{
				fprintf(stderr, "fastest page %d: %dms (interpretation) %dms (rendering) %dms(total)\n",
					timing.minpage, timing.mininterp, timing.min - timing.mininterp, timing.min);
				fprintf(stderr, "slowest page %d: %dms (interpretation) %dms (rendering) %dms(total)\n",
					timing.maxpage, timing.maxinterp, timing.max - timing.maxinterp, timing.max);
			}
			else
			{
				fprintf(stderr, "fastest page %d: %dms\n", timing.minpage, timing.min);
				fprintf(stderr, "slowest page %d: %dms\n", timing.maxpage, timing.max);
			}
		}
		else
		{
			fprintf(stderr, "total %dms / %d pages for an average of %dms in %d files\n",
				timing.total, timing.count, timing.total / timing.count, files);
			fprintf(stderr, "fastest page %d: %dms (%s)\n", timing.minpage, timing.min, timing.minfilename);
			fprintf(stderr, "slowest page %d: %dms (%s)\n", timing.maxpage, timing.max, timing.maxfilename);
		}
	}

	if (num_workers > 0)
	{
		for (i = 0; i < num_workers; i++)
		{
			workers[i].band = -1;
			SEMAPHORE_TRIGGER(workers[i].start);
			SEMAPHORE_WAIT(workers[i].stop);
			SEMAPHORE_FIN(workers[i].start);
			SEMAPHORE_FIN(workers[i].stop);
			THREAD_FIN(workers[i].thread);
			fz_drop_context(workers[i].ctx);
		}
		fz_free(ctx, workers);
	}

	if (bgprint.active)
	{
		bgprint.pagenum = -1;
		SEMAPHORE_TRIGGER(bgprint.start);
		SEMAPHORE_WAIT(bgprint.stop);
		SEMAPHORE_FIN(bgprint.start);
		SEMAPHORE_FIN(bgprint.stop);
		THREAD_FIN(bgprint.thread);
		fz_drop_context(bgprint.ctx);
	}

	fz_drop_context(ctx);
	LOCKS_FIN();

	if (showmemory)
	{
		fprintf(stderr, "Total memory use = " FMT_zu " bytes\n", memtrace_total);
		fprintf(stderr, "Peak memory use = " FMT_zu " bytes\n", memtrace_peak);
		fprintf(stderr, "Current memory use = " FMT_zu " bytes\n", memtrace_current);
	}

	return (errored != 0);
}