File: pstoimg.pin

package info (click to toggle)
latex2html 2008-debian1-7
  • links: PTS
  • area: main
  • in suites: wheezy
  • size: 11,176 kB
  • sloc: perl: 30,941; makefile: 429; sh: 155
file content (1834 lines) | stat: -rwxr-xr-x 50,969 bytes parent folder | download | duplicates (4)
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
#- -*- perl -*-
#-
#- This is the master pstoimg script. The configure procedure
#- builds the final perl script out of this file. These lines,
#- starting with `#-' are discarded.
#-
#- The traditional #! line will be inserted automatically
#-
##############################################################################
# $Id: pstoimg.pin,v 1.19 2004/01/02 08:20:33 RRM Exp $
#
# pstoimg
#
# Accompanies LaTeX2HTML
#
# Script to convert an arbitrary PostScript image to a cropped GIF or PNG
# image suitable for incorporation into HTML documents as inlined images
# to be viewed with WWW browsers.
#
# This software is provided as is without any guarantee.
#
##############################################################################
#
# $Log: pstoimg.pin,v $
# Revision 1.19  2004/01/02 08:20:33  RRM
#  --  support  -interlace (as identical to  -interlaced) so as not to
#      run afoul when  $POSIXLY_CORRECT  is set.
#
# Revision 1.18  2004/01/02 06:51:03  RRM
#  --  set the default transparent-color for PNG to 'gray85'
#  --  allow the transparent-color to be set using an environment variable
#        $ENV{'TRANSPARENT_COLOR'}
#
# Revision 1.17  2003/12/31 15:06:21  RRM
#  --  fixed bug stopping  -depth 24  from working
#      thanks to Tino Keitel <tino.keitel@web.de>  for the report.
#
# Revision 1.16  2001/10/25 10:16:12  RRM
#  --  make sure that $PNMCROPOPT  is declared before @PNMCROPOPT@
#
# Revision 1.15  2001/08/21 10:48:59  RRM
#  --  corrects errors in implementing $PNMCROPOPT
#
# Revision 1.14  2001/08/20 08:51:20  RRM
#  --  implement @PNMCROPOPT@ for the arguments to $PNMCROP
#      This is needed for v9.12+ of  pnmcrop .
#  --  when shaving fails, don't try to copy or rename
#
# Revision 1.13  2001/03/27 09:27:38  RRM
#  --  inserted missing '$' for  $edge .
#
# Revision 1.12  2001/03/25 02:05:14  RRM
#  --  implement the temporary hack to pnmcrop, using -black to help detect
# 	the correct color for cropping-bars; only workd with black bars.
#      A complete fix will be available with Netpbm v9.12 .
#
# Revision 1.11  1999/10/25 21:18:22  MRO
#
# -- added more configure options (Jens' suggestions)
# -- fixed bug in regexp range reported by Achim Haertel
# -- fixed old references in documentation (related to mail list/archive)
#
# Revision 1.10  1999/10/06 22:04:13  MRO
#
# -- texexpand: latex2html calls texexpand with the -out option instead of
#    output redirection: this is safer on non-UNIX platforms
# -- pstoimg: now there's no default cropping (useful for standalone
#    conversions). latex2html was changes appropriately
# -- minor cleanups in latex2html script and documentation
#
# Revision 1.9  1999/09/14 22:02:02  MRO
#
# -- numerous cleanups, no new features
#
# Revision 1.8  1999/07/19 09:51:00  RRM
#  --  added  -aaliastext  switch, for easier way to specify anti-aliased
#      font characters, without also anti-aliasing other graphics objects.
#
# Revision 1.7  1999/06/24 07:28:59  MRO
#
#
# -- removed L2HMODULE
# -- fixed processing of -info switch
# -- changed option order for dvips on win32 (thanks JCL)
# -- bumped version to 99.2a8
#
# Revision 1.6  1999/06/06 14:24:50  MRO
#
#
# -- many cleanups wrt. to TeXlive
# -- changed $* to /m as far as possible. $* is deprecated in perl5, all
#    occurrences should be removed.
#
# Revision 1.5  1999/06/04 20:14:25  MRO
#
#
# -- Reworked option parsing completely. Should behave much the same as before,
#    options with -no_* work just like before.
# -- Changed $NOFORK to $CAN_FORK and inverted the logic.
# -- Small debugging enhancement in pstoimg
#
# Revision 1.4  1999/06/04 15:30:15  MRO
#
#
# -- fixed errors introduced by cleaning up TMP*
# -- made pstoimg -quiet really quiet
# -- pstoimg -debug now saves intermediate result files
# -- several fixes for OS/2
#
# Revision 1.3  1999/06/01 06:55:35  MRO
#
#
# - fixed small bug in L2hos/*
# - added some test_mode related output to latex2html
# - improved documentation
# - fixed small bug in pstoimg wrt. OS2
#
# Revision 1.2  1999/05/17 21:30:59  MRO
#
#
# -- make texexpand warning-free and start making it use strict
#    compliant
#
# Revision 1.1  1999/05/11 06:10:00  MRO
#
#
# - merged config stuff, did first tries on Linux. Simple document
#   passes! More test required, have to ger rid of Warnings in texexpand
#
# Revision 1.18  1999/05/05 19:47:03  MRO
#
#
# - many cosmetic changes
# - final backup before merge
#
# Revision 1.17  1999/03/15 23:00:53  MRO
#
#
# - moved L2hos modules to top level directory, so that no dir-
#   delimiter is necessary in the @INC-statement.
# - changed strategy for "shave": Do not rely on STDERR redirection any
#   more (caused problems on at least Win32)
#
# Revision 1.16  1999/02/14 23:44:34  MRO
#
#
# -- first attempt to fix Win32 problems
#
# Revision 1.15  1999/02/11 00:18:29  MRO
#
#
# -- cleaned up warppers, TeXlive stuff and Makefile
#
# Revision 1.14  1999/02/10 01:37:12  MRO
#
#
# -- changed os-dependency structure again - now neat OO modules are
#    used: portable, extensible, neat!
# -- some minor cleanups and bugfixes
#
# Revision 1.13  1998/12/07 23:19:58  MRO
#
#
# -- added POD documentation to pstoimg and did a general cleanup
# -- some finetuning of config procedure and modules
#
# Revision 1.12  1998/10/31 14:13:05  MRO
# -- changed OS-dependent module loading strategy: Modules are now located in
#    different (OS-specific) directories nut have the same name: Easier to
#    maintain and cleaner code
# -- Cleaned up config procedure
# -- Extended makefile functionality
#
# Revision 1.11  1998/08/09 20:45:20  MRO
# -- some cleanup
#
# Revision 1.10  1998/06/14 14:10:38  latex2html
# -- Started to implement TeXlive configuration and better OS specific
#    handling (Batch files)                              (Marek)
#
# Revision 1.9  1998/06/07 22:35:24  latex2html
# -- included things I learned from the Win95 port to config procedure:
#    GS_LIB, Win32 module calls, directory separator stuff, ... (Marek)
#
# Revision 1.8  1998/06/01 12:57:56  latex2html
# -- Cleanup and cosmetics.
#
# Revision 1.7  1998/05/14 22:27:37  latex2html
# -- more work on config procedure (Makefile, GS_LIB)
# -- tested pstoimg in 98.1 environment successfully on Linux
#
# Revision 1.6  1998/05/06 22:31:09  latex2html
# -- Enhancements to the config procedure: Added a "generic" target
#    in the Makefile for the TeXlive CD (not perfect yet)
# -- included test for kpsewhich / Web2C
# -- included latest stuff from Override.pm into os_*.pm
#
# Revision 1.5  1998/04/28 22:18:11  latex2html
# - The platform specific stuff is now kept in a separate perl module. This
#   does not introduce significant overhead and enhances maintainability.
#
# Revision 1.4  1998/03/19 23:38:06  latex2html
# -- made pstoimg plug-in compatible with old one (touchwood!)
# -- cleaned up, added some comments
# -- inserted version information output
# -- incorporated patches to make OS/2 run better (thanks Uli)
# -- updated Makefile: make, make test, make install should work now
#
# Revision 1.3  1998/03/11 23:44:00  latex2html
# -- cleaned up config.pl and reworked dvips checks
# -- got pstoimg.pin up to par with the regular pstoimg
# -- cosmetic changes
# -- runs now under Win95 with Fabrice Popineau's Win32 tools (gs, TeX,...)
#
# Revision 1.2  1998/03/02 23:38:40  latex2html
# Reworked configuration procedure substantially. Fixed some killing bugs.
# Should now run on Win32, too.
# The file prefs.pm contains user-configurable stuff for DOS platforms.
# UNIX users can override the settings with the configure utility (preferred).
#
# Revision 1.1  1998/02/14 19:31:55  latex2html
# Preliminary checkin of configuration procedure
#
# (end CVS log)
###############################################################################

#- The following lines are a warning to the unwary
# This file has been automatically generated by build.pl from pstoimg.pin
# Do not edit this file as your changes will be lost when reconfiguring.
# If you want to supply patches, please apply them to pstoimg.pin and send
# the diff relative to the original pstoimg.pin. Thank you.

=head1 NAME

pstoimg - Convert a PostScript file to a bitmap image using 
Ghostscript and the Netpbm utilities

=cut

use 5.003;
use strict;
#use diagnostics;
use vars qw(*SAVEERR $LATEX2HTMLDIR $SCRIPT);

# This variable points to the DIRECTORY where the latex2html files
# can be found.

use Getopt::Long;

#- the (texlive) wrapper sets these values
#- or it is stored in the enviroment

# see below for a description of the environment

#unless @wrapper@ || @texlive@
BEGIN {
  # print "scanning for l2hdir\n";
  if($ENV{LATEX2HTMLDIR}) {
    $LATEX2HTMLDIR = $ENV{LATEX2HTMLDIR};
  } else {
    $ENV{LATEX2HTMLDIR} = $LATEX2HTMLDIR = '@LATEX2HTMLDIR@';
  }

  if(-d $LATEX2HTMLDIR) {
    push(@INC,$LATEX2HTMLDIR);
  } else {
    die qq{Fatal: Directory "$LATEX2HTMLDIR" does not exist.\n};
  }
}
#fi

use L2hos; # load OS-specific stuff

my $RELEASE = '@distver@';
my ($VERSION) = q$Revision: 1.19 $ =~ /:\s*(\S+)/;

$| = 1; # unbuffer STDOUT

my $dd = L2hos->dd; # Directory delimiter
my $prompt;
($prompt = $0) =~ s|^.*[/\\]||;

# Configuration as determined by "configure"
#
# Ghostscript
my $GS = '@GS@';
my $GSDEVICE = '@GSDEVICE@';
#if @GSALIASDEVICE@
my $GSALIASDEVICE = '@GSALIASDEVICE@';
#fi
#-
#if @GS_LIB@
# Set path for ghostscript fonts and libraries
$ENV{GS_LIB} = '@GS_LIB@' unless(defined $ENV{GS_LIB});
#fi
#if !@have_geometry@ && @GSLANDSCAPE@ && @PNMFLIP@
# This gives the location of the file landscap.ps
# only needed for &choose_paper
my $GSROTATE = ''; # no rotation by default
my $GSLANDSCAPE = '@GSLANDSCAPE@';
my $GS_UNROTATE = 'cw'; # pnmflip switch to undo landscape rotation
#fi
#-
# Supported format(s)
my @IMAGE_TYPES = qw(@IMAGE_TYPES@);
#-
# Netpbm
my $PNMCROP = '@PNMCROP@';
my $PNMCROPOPT = '';
#if @PNMBLACK@
my $PNMBLACK = '@PNMBLACK@';
$PNMCROPOPT = $PNMBLACK;
#fi
#if @PNMCROPOPT@
$PNMCROPOPT = '@PNMCROPOPT@';
#fi
#if @PPMQUANT@
my $PPMQUANT = '@PPMQUANT@';
#fi
#-
#if @PNMFLIP@
my $PNMFLIP = '@PNMFLIP@';
#fi
#-
#if @PNMCAT@ && @PNMFILE@ && @PBMMAKE@ # can justify
my $PNMCAT = '@PNMCAT@';
my $PNMFILE = '@PNMFILE@';
my $PBMMAKE = '@PBMMAKE@';
#fi
#-
#if @IMAGE_TYPES@ =~ /gif/i
# GIF support
my $PPMTOGIF = '@PPMTOGIF@';
#if @GIFTRANS@
my $GIFTRANS = '@GIFTRANS@';
#fi
#if @GIFTOOL@
my $GIFTOOL = '@GIFTOOL@';
#fi
#fi
#-
#if @IMAGE_TYPES@ =~ /png/i
# PNG support
my $PNMTOPNG = '@PNMTOPNG@';
#fi
#-
# Temporary diskspace
my $def_tmp = '@TMPSPACE@'; # Space for temporary files

# Some lengths used by dvips
# MRO: Is this true for all runs of dvips?

my $PAGE_HEIGHT = 841.889;   # dvips page height, in pts.
my $PAGE_WIDTH  = 595.275;   # dvips page width, in pts.
my $PAGE_HMARGIN = 72;       # dvips margin: 1 inch = 72pt
my $PAGE_VMARGIN = 72;       # dvips margin: 1 inch = 72pt

# The color to be made transparent
my $TRANSPARENT_COLOR = $ENV{'TRANSPARENT_COLOR'}||'';
my $trans_color = $TRANSPARENT_COLOR||'#ffffff';

###############################################################################
# Default settings
# Environment overrides defaults, command line options override everything

unless(@ARGV) {
  print_help();
  exit 0;
  }

=head1 SYNOPSIS

B<pstoimg> B<-help> | B<-version>

B<pstoimg>
S<[ B<-antialias> ]>
S<[ B<-aaliastext> ]>
S<[ B<-center> I<num> ]>
S<[ B<-color> I<num> ]>
S<[ B<-crop> I<code> ]>
S<[ B<-debug> ]>
S<[ B<-density> I<num>]>
S<[ B<-depth> I<num> ]>
S<[ B<-discard> ]>
S<[ B<-flip> I<code> ]>
S<[ B<-geometry> I<X>xI<Y> ]>
S<[ B<-interlaced> ]>
S<[ B<-margins> I<X>,I<Y> ]>
S<[ B<-multipage> ]>
S<[ B<-out> I<file> ]>
S<[ B<-quiet> ]>
S<[ B<-rightjustify> I<num> ]>
S<[ B<-scale> I<num> ]>
S<[ B<-tmp> I<path> ]>
S<[ B<-topjustify> [B<x>]I<num> ]>
S<[ B<-transparent> ]>
S<[ B<-type> I<type> ]>
S<[ B<-shoreup> I<num>[B<d>] ]>
S<[ B<-white> ]>
I<file>
S<[ I<file2> ... ]>

=cut

my %opt = ();
unless(&GetOptions(\%opt, qw(-help -version -debug -discard -antialias -aaliastext
  -multipage -type=s -gif -png -out=s -depth=i -color=i -flip=s -density=i
  -scale=f -geometry=s -margins=s -crop=s -transparent -interlaced -interlace
  -rightjustify=i -center=i -topjustify=s -shoreup=s -tmp=s -white -quiet))) {
  print_usage("$prompt: Error: Invalid option(s) specified.");
  exit 1;
}

=head1 OPTIONS

The command line options may be abbreviated to the shortest unique
prefix.

=over 4

=item B<-help>

Show this help page and exit.

=cut

if($opt{help}) {
  print_help();
  exit 0;
  }

=item B<-version>

Show the release and version of pstoimg and exit.

=cut

if($opt{version}) {
  print_version();
  exit 0;
  }

banner() unless($opt{quiet});

=item B<-antialias>

Use Ghostscript's anti-aliasing feature for rendering "softer" images.
This applies to lines and edges of polygonal and oval or circular shapes.
Only valid if Ghostscript 4.03 or higher is installed.

=item B<-aaliastext>

Use Ghostscript's anti-aliasing feature for "smoother" font characters,
without the jagged edges. Similar to B<-antialias> for graphic components.
Only valid if Ghostscript 4.03 or higher is installed.

=item B<-center> I<num>

Add the appropriate amount of whitespace to the left of the image so
that the image appears to be centered in a total width of I<num> pixels.

=cut

my $CENTER = 0; # No centering by default
if($opt{center}) {
#if @PNMCAT@ && @PNMFILE@ && @PBMMAKE@ # can justify
  $CENTER = $opt{center};
  die <<"EOF" unless ($CENTER =~ /^\d+$/ && $CENTER > 0);
$prompt: Error: Illegal width for -center specified: "$CENTER"
         Value must be a positive integer.
EOF
#else
  die "$prompt: Error: Cannot center-justify on this installation.\n";
#fi
  }

=item B<-crop> I<code>

Crop the bitmap from the given directions. I<code> may be a string of
several cropping instructions, which are executed strictly in the given
order. Possible values are: B<h> (horizontal, i.e. crop top and
bottom), B<v> (vertical), B<tblr> (top, bottom, left, right) and B<a> (all
directions). A special case is B<s>: "shave" the image at the bottom, but only
if a single line of whitespace exists.

=cut

my $EXTRA_CROP = '';
if($opt{crop}) {
  $EXTRA_CROP = lc($opt{crop});
  die <<"EOF" unless ( $EXTRA_CROP =~ /^([vhtblras]+)$/i );
$prompt: Error: Illegal crop specified: "$EXTRA_CROP"
         Crop must be  h, v, t, b, l, r, a, s  or combination
EOF
  }

=item B<-debug>

Turn on debugging output. This can get rather verbose. Any intermediate
files generated are not removed to help debugging.

=cut

if($ENV{DEBUG}) {
  $opt{debug} = 1;
  }

=item B<-density> I<num>

The density (resolution) in DPI in which to render the bitmap. The default
is 72.

=cut

my $DENSITY = 72;
if($opt{density}) {
  $DENSITY = $opt{density};
  }
elsif($ENV{DENSITY}) {
  $DENSITY = $ENV{DENSITY};
  }
die <<"EOF" unless $DENSITY =~ /^\d+$/;
$prompt: Error: Illegal density specified: "$DENSITY"
         Density must be an integer value. Default is 72.
EOF

=item B<-depth> I<num> or B<-color> I<num>

Specify the color depth of the bitmap. Legal values are 1 (black & white),
8 (256 colors) and 24 (true color).

=cut

unless($opt{depth}) {
  if($opt{color}) {
    $opt{depth} = $opt{color};
    }
  elsif($ENV{DEPTH}) {
    $opt{depth} = $ENV{DEPTH};
    }
  else {
    $opt{depth} = 8;
    }
  }
die <<"EOF" unless $opt{depth} =~ /^(1|8|24)$/;
$prompt:  Error: Illegal color depth specified: "$opt{depth}"
          Depth must be either 1, 8 or 24.
EOF

=item B<-discard>

Delete the input postscript file if the conversion was successful. Setting
the environment DISCARD to a true value (as perl sees it) has the same
effect.

=cut

if($ENV{DISCARD}) {
  $opt{discard} = 1;
  }

=item B<-flip> I<code>

Flip all generated output bitmaps. The following codes are recognized:
lr (flip left-right), tb (flip top-bottom), xy (flip bottom/left-top/right),
r90 and ccw (rotate by 90 degrees counterclockwise), r270 and cw (rotate
90 degrees clockwise) and r180 (rotate 180 degrees).

=cut

if($opt{flip}) {
#if @PNMFLIP@
  $opt{flip} = lc($opt{flip});
  die <<"EOF" unless $opt{flip} =~ /^(lr|tb|xy|r90|ccw|r270|cw|r180)$/;
$prompt: Error: Illegal flip option specified: "$opt{flip}"
         Flip must be one of: lr tb xy r90 ccw r270 cw r180
EOF
#else
  print "$prompt: Warning: -flip option not supported.\n";
#fi
  }

=item B<-geometry> I<X>xI<Y>

Render only this "window" of the PostScript file. If given, this option
can dramatically reduce memory requirements and speed up conversion. The
geometry is automatically detected in case of EPS files (Encapsulated
PostScript).

=cut

my $GEOMETRY = '';
if($opt{geometry}) {
  $GEOMETRY = $opt{geometry};
  if($GEOMETRY =~ s/-//o ) {
    $EXTRA_CROP .= 'bl';
    }
  die <<"EOF" unless ($GEOMETRY =~ /^\d+x\d+$/i);
$prompt: Error: Illegal geometry specified: "$GEOMETRY"
         Geometry must be <width>x<height>
EOF
  }

=item B<-interlaced>

Generate an interlaced bitmap. Interlaced images build up from coarse to
fine as they are loaded. This option may not work on every installation
and/or bitmap type, depending of the capabilities of external programs.

=cut

my $INTERLACE = 0; # Do not make interlaced images by default
if($opt{interlaced}||$opt{interlace}) {
#unless @gif_interlace@
  if($opt{type} eq 'gif') {
    print "$prompt: Warning: Interlaced GIFs not supported.\n";
    }
#fi
  $INTERLACE=1;
  }

=item B<-margins> I<X>,I<Y>

The offset of the rectangle in the postscript file that is going to be
rendered from top/left. Can be used together with B<-geometry> to further
reduce the size of the intermediate bitmap file generated by Ghostscript.

=cut

if($opt{margins}) {
  die <<"EOF" unless (($opt{margins} =~ /^(\d+),(\d+)$/));
$prompt: Error: Illegal margins specified: "$opt{margins}"
         Margins must be <hmargin>,<vmargin>
EOF
  $PAGE_HMARGIN = $1;
  $PAGE_VMARGIN = $2;
  }

=item B<-multipage>

Process a multi-page PostScript file, i.e. create an individual bitmap
for every page. The resulting files are numbered: The decimal number
(starting with 1) is appended to the basename of the PostScript input
file (or the basename of the filename specified with B<-out>), while
keeping the extension.

=item B<-out> I<file>

The file where to write the bitmap. If multiple PostScript files are
supplied on the command line, this option is ignored. The bitmap type
extension is appended automatically if I<file> does not contain a dot.
In connection with B<-multipage> I<file> is extended by the page number
as shown in this example:

-outfile foo.gif  --------E<gt> foo1.gif, foo2.gif, ...

=cut

if(!$opt{out} && $ENV{OUTFILE}) {
  $opt{out} = $ENV{OUTFILE};
  }

=item B<-quiet>

Do not print anything except error messages.

=item B<-rightjustify> I<num>

Add the appropriate amount of whitespace to the left of the image so that
it appears to be aligned to the right in a total width of I<num> pixels.

=cut

my $RIGHT_JUSTIFY = 0; # No right justifying by default
if($opt{rightjustify}) {
#if @PNMCAT@ && @PNMFILE@ && @PBMMAKE@ # can justify
  $RIGHT_JUSTIFY = $opt{rightjustify};
  die <<"EOF" unless ($RIGHT_JUSTIFY =~ /^\d+$/ && $RIGHT_JUSTIFY > 0);
$prompt: Error: Illegal width for -rightjustify specified: "$RIGHT_JUSTIFY"
         Value must be a positive integer.
EOF
#else
  die "$prompt: Error: Cannot right-justify on this installation.\n";
#fi
  }

=item B<-scale> I<factor>

Scale the image by I<factor>. Valid choices are any numbers greater than
zero. Useful choices are numbers between 0.1 - 5.
Large numbers may generate very large intermediate files and will take
longer to process. If this option is omitted, the environment SCALE is
considered.

=cut

unless($opt{scale}) {
  if($ENV{SCALE}) {
    $opt{scale} = $ENV{SCALE};
    }
  else {
    $opt{scale} = 1;
    }
  }
die <<"EOF" unless ($opt{scale} =~ /^[\d.e]+$/i && $opt{scale} > 0);
$prompt: Error: Illegal scale specified: "$opt{scale}"
         Scale must be nonnegative float value.
EOF

=item B<-shoreup> I<num>[B<d>]

Make height and width of the bitmap(s) an exact multiple of I<num>. If
I<num> is followed by a "d", then half the extra vertical space is placed
underneath. This option is useful, if you want to have "blown-up" images
of high quality for print, but downscale them in HTML using
C<E<lt>IMG WIDTH=x HEIGHT=yE<gt>>. If the actual image is is not an
integer multiple of x,y then browsers tend to display distorted images.

=cut

my $SHORE_UP = 0; # No pixel alignment by default
if($opt{shoreup}) {
  $SHORE_UP = $opt{shoreup};
  die <<"EOF" unless $SHORE_UP =~ /^\d+d?$/i;
$prompt: Error: Illegal shore-up specified: "$SHORE_UP"
         Value must be a positive integer, optionally followed by d
EOF
  }

=item B<-tmp> I<path>

Use I<path> to store temporary files. Defaults to @TMPSPACE@ on this
installation. This parameter can be set by the environment B<TMP> or 
B<TEMP>, too.

=cut

my $TMP = '';
if($opt{tmp}) {
  $opt{tmp} =~ s|\Q$dd\E+$||; # remove trailing directory separator(s)
  if(-d $opt{tmp} && -r _ && -w _) {
    $TMP = $opt{tmp};
  } else {
    print "$prompt: Warning: Cannot use $opt{tmp} as temporary directory.\n";
  }
}
if(!$TMP && ($ENV{TMP} || $ENV{TEMP})) {
  ($opt{tmp} = $ENV{TMP} || $ENV{TEMP}) =~ s|\Q$dd\E+$||;
  if(-d $opt{tmp} && -r _ && -w _) {
    $TMP = $opt{tmp};
  } else {
    print "$prompt: Warning: Cannot use $opt{tmp} as temporary directory.\n";
  }
}
if(!$TMP && -d $def_tmp && -r _ && -w _) {
  $TMP = $def_tmp;
}
print "$prompt: Temporary directory is $TMP\n" if($opt{debug});

=item B<-topjustify> [B<x>]I<num>

Add padding whitespace to the image so that it gets a defined height.
If an integer value is given, it defines the total height. The whitespace
is added at the bottom. If the number is preceded by "x", then this
multiple of the image height is added as whitespace at the bottom.

=cut

my $TOP_JUSTIFY = 0; # No top justifying by default
if($opt{topjustify}) {
#if @PNMCAT@ && @PNMFILE@ && @PBMMAKE@ # can justify
  $TOP_JUSTIFY = $opt{topjustify};
  die <<"EOF" unless $TOP_JUSTIFY =~ /^x?\d+[.]?\d*$/i;
$prompt: Error: Illegal align specified: "$TOP_JUSTIFY"
         Value must be positive numeric, optionally preceded by x
EOF
#else
  die "$prompt: Error: Cannot top-justify on this installation.\n";
#fi
  }

=item B<-transparent>

Generate transparent bitmaps, i.e. the background color (white) is
transparent if viewed with certain viewers (e.g. browsers). This option
may not be available due to missing capabilities of external
programs.

=cut

my $TRANSPARENT = 0; # Do not make make images transparent by default
if($opt{transparent}) {
  $TRANSPARENT = 1;
  }

=item B<-type> I<type>

Instruct pstoimg to render the bitmap in I<type> format. Depending on 
the local installation, pstoimg is capable of generating either GIF or
PNG bitmaps. This site features the following types: @IMAGE_TYPES@

If omitted, the first type in this list is taken.

=cut

if($opt{type}) {
  $opt{type} = lc($opt{type});
  die <<"EOF" unless grep($_ eq $opt{type},@IMAGE_TYPES);
$prompt: Error: This version of pstoimg does not support
    "$opt{type}" image format.
EOF
  }
else {
  ($opt{type}) = @IMAGE_TYPES; # default image type
  }
# Support -gif and -png for a transition period
if($opt{gif}) {
  print qq{$prompt: Warning: The -gif switch is deprecated. Use "-type gif" instead.\n};
  if(grep($_ eq 'gif',@IMAGE_TYPES)) {
    $opt{type} = 'gif';
    }
  else {
    die <<"EOF";
$prompt: Error: This version of pstoimg does not support "gif" format.
EOF
    }
  }
if($opt{png}) {
  print qq{$prompt: Warning: The -png switch is deprecated. Use "-type png" instead.\n};
  if(grep($_ eq 'png',@IMAGE_TYPES)) {
    $opt{type} = 'png';
    }
  else {
    die <<"EOF";
$prompt: Error: This version of pstoimg does not support "png" format.
EOF
    }
  }

=item B<-white>

Remove TeX's page color information from the PostScript file before 
converting so that a white background is used.

=back

=cut

# do some consistency checks on the options

#unless @gif_trans@
if($TRANSPARENT && $opt{type} eq 'gif') {
  print "$prompt: Warning: Transparent GIFs not supported.\n";
  }
#fi

die <<"EOF" if($RIGHT_JUSTIFY && $CENTER);
$prompt: Error: Conflicting options -center and -rightjustify.
EOF

# now setup some parameters

# calculate dpi resolution from density and scale
$DENSITY = int($opt{scale} * $DENSITY + .5) if($opt{scale} != 1);

#if @PPMQUANT@
my $reduce_color = '';
if($opt{depth} == 1) {
  $reduce_color = "$PPMQUANT 2";
  }
elsif ($opt{depth} == 8) {
  $reduce_color = "$PPMQUANT 256";
  }
#fi

my $gs_aalias = '';
#if @GSALIASDEVICE@
if($opt{antialias}) {
  $GSDEVICE = $GSALIASDEVICE;
  if($opt{depth} == 1) { 
    $gs_aalias = '-dTextAlphaBits=4 ';
#if @PPMQUANT@
    $reduce_color = "$PPMQUANT -floyd 256";
#fi
    }
  else {
    $gs_aalias = '-dTextAlphaBits=4 -dGraphicsAlphaBits=4 ';
    }
  }
elsif ($opt{aaliastext}) {
  $GSDEVICE = $GSALIASDEVICE;
    $gs_aalias = '-dTextAlphaBits=4 ';
#if @PPMQUANT@
    $reduce_color = "$PPMQUANT -floyd 256";
#fi
  }
#fi
#-
my $PAPERSIZE = $ENV{PAPERSIZE} || '';
# This rx matches float values in Bounding Box expressions
my $Brx = '-?\d+(?:\.\d*|)';

##############################################################################
# Main program

=head1 DESCRIPTION

B<pstoimg> iterates over the given input files and runs them through
Ghostscript. The resulting pnm (portable anymap files) are processed
with different Netpbm tools (cropping, color mapping, aligning, ...)
and finally converted into (currently) either GIF or PNG format. The
bitmaps can now be included e.g. in WWW pages.

The PostScript file is converted as is. If a valid bounding box is
found (EPS format), then only this area is converted. The image is
I<not> cropped by default.

=cut

die "$prompt: Error: No input file(s) specified\n"
  unless(@ARGV);

# suppress diagnostics messages if possible
#if @texlive@
my $NULLFILE = L2hos->nulldev();
open(STDERR, ">$NULLFILE") if($NULLFILE && !$opt{debug});

#else
  #if @NULLFILE@
my $NULLFILE = '@NULLFILE@';
open(STDERR, ">$NULLFILE") unless($opt{debug});

  #fi
#fi - texexpand
my $exit = 0;

$opt{out} = '' if(@ARGV > 1); # disable -out if multiple ps files given

my $psfile;
foreach $psfile (@ARGV) {
  unless (-f $psfile) {
    print qq{$prompt: Error: Cannot find file "$psfile": $!\n};
    exit 1;
  }
  $exit += (&pstoimg($psfile) ? 0 : 1);
}

=head1 RETURN VALUE

=over 4

=item 0

if everything went all right

=item x

(x != 0) something went wrong. See the message output.

=back

=cut

exit $exit ? 1 : 0;

##############################################################################
# Subroutines

sub pstoimg {
  my ($psfile) = @_;

  print "$prompt: Processing $psfile\n" unless($opt{quiet});
  # remove a trailing suffix the same way a shell would do it
  my $base = $psfile;
  $base =~ s|[.][^.$dd$dd]*$||;

  my $outfile;
  if($opt{out}) {
    $outfile = $opt{out};
    # append the type unless -outfile has a "." in it
    $outfile .= ".$opt{type}" unless($outfile =~ /[.]/);
  }
  else {
    $outfile = "$base.$opt{type}";
  }

  # Invoke Ghostscript
  my $pnmdir = $TMP ? "$TMP$dd" : ".$dd";
  my $pnmbase = "p$$"; # keep it short for dos
  my $pnmfile = $pnmdir . 
    ($opt{multipage} ? "%d_${pnmbase}.pnm" : "$pnmbase.pnm");

  ps2pnm($psfile,$pnmfile) || return 0;

  my $ok = 1;
  if (-f $pnmfile) {
    if(crop_scale_etc($pnmfile, $outfile)) {
      L2hos->Unlink($pnmfile) unless($opt{debug});
      }
    else {
      return 0;
      }
    }
  elsif($opt{multipage}) {
    unless(opendir(DIR,$pnmdir)) {
      print qq{$prompt: Error: Could not open directory "$pnmdir": $!\n};
      return 0;
      }
    my @list = grep(/^\d+_${pnmbase}\.pnm/,readdir(DIR));
    closedir(DIR);
    if(@list) {
      my $i;
      foreach $i (@list) {
        my ($n) = $i =~ /^(\d+)_/;
        my $j = $outfile;
        $j =~ s|(\.[^/.]*)$|$n$1|;
	if(crop_scale_etc("$pnmdir$i", $j)) {
          L2hos->Unlink("$pnmdir$i") unless($opt{debug});
          }
        else {
          $ok = 0;
          }
        }
      }
    else {
      goto not_found;
      }
    }
  else {
    not_found:
    print "$prompt: Error: Couldn't find pnm output of $psfile\n";
    }
  L2hos->Unlink($psfile) if($opt{discard} && !$opt{debug});
  $ok;
  }

sub ps2pnm {
  my ($psfile,$pnmfile) = @_;
  my $gs_size = $PAPERSIZE ? "-sPAPERSIZE=$PAPERSIZE" : '';
  my $gs_density = ($DENSITY != 72) ? "-r$DENSITY" : '';

  my ($bbx, $bby, $bbw, $bbh) = (0,0,0,0);
  my $max_lines = 100;
  my ($epsf,$have_geometry) = (0,0);

  # Parse postscript file for information
  unless(open(PS, "<$psfile")) {
    print qq{$prompt: Error: Cannot read "$psfile": $!};
    return 0;
    }
  $_ = <PS>; # read one line
  if( /^%!.*EPSF/ ) {
    # we're in a EPSF file
    $epsf = 1;
    }
  if($GEOMETRY || $epsf) {
    while (defined ($_ = <PS>)) {
      # Look for bounding box comment
      # MRO: add support of precise bounding boxes
      if ($epsf && (
        /^%+(?:HiRes|Exact)BoundingBox:\s+($Brx)\s+($Brx)\s+($Brx)\s+($Brx)/o ||
        /^\%\%BoundingBox:\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)\s+(-?\d+)/)) {
        $bbx = 0 - $1;    $bby = 0 - $2;
        $bbw = $3 + $bbx; $bbh = $4 + $bby;
        if(($bbw > 0) && ($bbh > 0)) { # we have a valid bounding box
          print "$prompt: EPSF dimensions are ${bbw}x$bbh\n" if($opt{debug});
          # this overrides the -geometry switch
          if($DENSITY) { # scale the output
            my $scale = $DENSITY / 72.0;
            $bbw *= $scale;
            $bbh *= $scale;
          }
          $bbw = int($bbw + 0.99);
          $bbh = int($bbh + 0.99);
          $GEOMETRY = "${bbw}x${bbh}";
          $have_geometry = 1;
          last;
          }
        }
      # Look for page size information
      elsif($GEOMETRY && /TeXDict\s+begin\s+(\d+)\s+(\d+)\s+/) {
        $PAGE_WIDTH  = int($1 / 65536 * 72 /72.27 +.5);
        $PAGE_HEIGHT = int($2 / 65536 * 72 /72.27 +.5);
        print "$prompt: Page dimensions are ${PAGE_WIDTH}x$PAGE_HEIGHT\n"
          if($opt{debug});
        # we don't have to look further for EPSF stuff at this point
        last;
        }
      elsif(!$GEOMETRY && (/^\%\%EndComments/ || --$max_lines == 0)) {
        # abort at a certain point to avoid scanning huge ps files
        last;
        }
      }
    }
  close PS;
  if($GEOMETRY && !$have_geometry) { # RRM: overrides $PAPERSIZE 
    # no geometry info found in the Postscript file
    $bbx = $PAGE_HMARGIN;
    $bby = $PAGE_HEIGHT - $PAGE_VMARGIN;
    unless($GEOMETRY =~ /\s*(\d+)x(\d+)/i) {
      print qq{$prompt: Illegal geometry "$GEOMETRY" specified.\n};
      return 0;
      }
    $bbw = $1 + 10;  # allow for the side-bars
    $bbh = $2;
    $bby = int(-$bby + $bbh + 8); # allow small margin for error
    $bbx = int(-$bbx + 5);        # allow small margin for error
    if($DENSITY) {
      my $scale = $DENSITY / 72.0;
      $bbw = int($scale * $bbw + .99);
      $bbh = int($scale * $bbh + .99);
      }
    $bbw += 10;  # add a 5pt margin for safety
    $bbh += 40;  # add a 20pt margin for safety
    $GEOMETRY = "${bbw}x$bbh";
    $have_geometry = 1;
    }
  if($have_geometry) {
#if @have_geometry@
    $gs_size = "-g$GEOMETRY ";
#else
    $gs_size = "-sPAPERSIZE=". &choose_paper($GEOMETRY);
#fi
    }

  my $ps_changed = 0;
  if($have_geometry || $opt{white}) {
    # Remove any Postscript commands concerning Papersize if -g switch is used
    # thanks to  Axel Ramge for identifying the problem and for this code
    local($/) = undef;
    open(PS,"<$psfile");
    my $ps = <PS>;
    close(PS);
    my $had_papersize;
    if($have_geometry) {
      $had_papersize = ($ps =~ s/\n%%BeginPaperSize.*?%%EndPaperSize[^\n]*\n/\n/sg);
      }
    my $had_nonwhite;
    if($opt{white}) {
      $had_nonwhite = ($ps =~ s/(\d+ \d+ bop gsave) \d*\.\d+ (TeXcolorgray clippath fill grestore)/$1 1 $2/s);
      }
    $ps_changed = $had_papersize || $had_nonwhite;
    if($ps_changed) {
      my $tmppsfile = $pnmfile; # was "tmpps$$.ps"
      $tmppsfile =~ s/\.[^.]*$/.ps/;
      unless(open(PS,">$tmppsfile") && (print PS $ps) && (close PS)) {
        if($had_papersize) {
          print <<"EOF";
$prompt: Warning: Could not write "$tmppsfile": $!
    "$psfile" contains %%Papersize comments.
    Any of these should be removed else GS will fail.
EOF
          }
        if($had_nonwhite) {
          print <<"EOF";
$prompt: Warning: Could not write "$tmppsfile": $!
    "$psfile" has a non-white background.
    This may cause ugly images.
EOF
          }
        }
      $psfile = $tmppsfile;
      print qq{Debug: Papersize comment in "$psfile" deleted.\n}
        if($had_papersize && $opt{debug});
      print qq{Debug: Background switched to white in "$psfile".\n}
        if($had_nonwhite && $opt{debug});
      }
    }

  my $gs_quiet = $opt{debug} ? '' : '-q -dNOPAUSE -dNO_PAUSE';
#if @texlive@
  my $out_redirect = ($NULLFILE && !$opt{debug}) ? "> $NULLFILE" : '';
#else
  #if @NULLFILE@
  my $out_redirect = $opt{debug} ? '' : "> $NULLFILE";
  #else
  my $out_redirect = '';
  #fi
#fi - texlive
  my $gs_out = "-sOutputFile=$pnmfile";
  my $gsfile = $psfile;
  # Ghostscript understands only '/' as path delimiter!
#if @texlive@
  $gsfile =~ s|\Q$dd|/|g if($dd ne '/');
#else
  #if @dd@ ne '/'
  $gsfile =~ s|\Q$dd|/|g;
  #fi
#fi - texlive
  if($opt{debug}) {
    print "$prompt: Running $GS $gs_quiet -sDEVICE=$GSDEVICE $gs_size $gs_density $gs_aalias $gs_out $out_redirect\n";
#if !@have_geometry@ && @PNMFLIP@ && @GSLANDSCAPE@
    print "GS>$GSROTATE\n" if($GSROTATE);
#fi
    print "GS>$bbx $bby translate\n" if($have_geometry);
    print "GS>($gsfile) run\n";
    print "GS>showpage\n" if ($epsf);
    print "GS>quit\n";
    }
  open (GS, "|$GS $gs_quiet -sDEVICE=$GSDEVICE $gs_size $gs_density $gs_aalias $gs_out $out_redirect");
#if !@have_geometry@ && @PNMFLIP@ && @GSLANDSCAPE@
  print GS "$GSROTATE\n" if ($GSROTATE);
#fi
  print GS "$bbx $bby translate\n" if ($have_geometry);
  print GS "($gsfile) run\n";
  print GS "showpage\n" if ($epsf);
  print GS "quit\n";
#if !@texlive@ && @NULLFILE@
  print "\n" if($opt{debug});
#else
  print "\n";
#fi
  unless(close(GS)) {
    print "$prompt: Error: Ghostscript returned error status ",$?>>8,"\n";
    }
  L2hos->Unlink($psfile) if($ps_changed && !$opt{debug});
  1;
  }

#- The following lines are needed if the -g switch is not recognized by gs
#unless @have_geometry@

sub choose_paper {
  my ($geometry) = @_;
  my ($size, $height, $width) = ('','','');
  unless($geometry =~ /^(\d*)\s*x\s*(\d*)$/i) {
    return 'a4';
    }
  else {
    $width=$1;
    $height=$2;
    }
#if @GSLANDSCAPE@ && @PNMFLIP@
  if($width > $height) {
    my $file = $GSLANDSCAPE;
    $file =~ s|\Q$dd|/|g; # gs understands only '/' as path delimiter
    $GSROTATE = "($file) run";
    ($width, $height) = ($height, $width);
    }
  else {
    $GSROTATE = '';
    }
#fi
  if   (($width < 74  ) && ($height < 105 )) { $size = "a10" }
  elsif(($width < 105 ) && ($height < 148 )) { $size = "a9"  }
  elsif(($width < 148 ) && ($height < 210 )) { $size = "a8"  }
  elsif(($width < 210 ) && ($height < 297 )) { $size = "a7"  }
  elsif(($width < 297 ) && ($height < 421 )) { $size = "a6"  }
  elsif(($width < 421 ) && ($height < 595 )) { $size = "a5"  }
  elsif(($width < 501 ) && ($height < 709 )) { $size = "b5"  }
  elsif(($width < 595 ) && ($height < 842 )) { $size = "a4"  }
  elsif(($width < 709 ) && ($height < 1002)) { $size = "b4"  }
  elsif(($width < 842 ) && ($height < 1190)) { $size = "a3"  }
  elsif(($width < 1002) && ($height < 1418)) { $size = "b3"  }
  elsif(($width < 1190) && ($height < 1684)) { $size = "a2"  }
  elsif(($width < 1418) && ($height < 2004)) { $size = "b2"  }
  elsif(($width < 1684) && ($height < 2380)) { $size = "a1"  }
  elsif(($width < 2004) && ($height < 2836)) { $size = "b1"  }
  elsif(($width < 2380) && ($height < 3368)) { $size = "a0"  }
  else                                       { $size = "b0"  }
  $size;
  }
#fi

# This sub post-processes the PNM images that come out of Ghostscript.
# The image is cropped, flipped and finally converted to PNG or GIF.

sub crop_scale_etc {
  my ($in, $out) = @_;

  # create temp filename; should be auto-incrementable
  my $tmp = $in;
  $tmp =~ s/(\.[^.]*)?$/.t00/;
  # save the original Ghostscript result
  if($opt{debug}) {
    L2hos->Copy($in,$tmp);
    &increment_name($tmp);
  }
  my ($cmd,$type,$width,$height,$just);

  my $must_align = 0;
  #$EXTRA_CROP = "a$EXTRA_CROP" # hack to ensure first all-over cropping
  #  unless($EXTRA_CROP =~ /^a/i);

  # RRM: Remove justification bars
  $EXTRA_CROP =~ s/h/bt/gi; # crop horizontally
  $EXTRA_CROP =~ s/v/rl/gi; # crop vertically
  while ($EXTRA_CROP =~ /([atblrs])/gi) {
    my $edge = $1;
    my $croparg = '';
    if($edge =~ /b/i) {
      $croparg = "-bot -sides $PNMCROPOPT ";
    } elsif($edge =~ /[tlr]/i) {
      $croparg = "-$edge -sides $PNMCROPOPT ";
    } elsif($edge =~ /s/i) {
      #RRM: shave at most 1-2 rows of white from the bottom
#if @pipes@
      if($cmd) {
        # Terminate command pipe
        &do_cmd($in,$tmp,$cmd) || return 0; # failure
        $cmd = '';
      }
#fi
      my ($type,$width,$height) = get_image_geometry($in);
      next unless($type); # skip if no geometry
      if(&do_cmd_norename("$PNMCROP $PNMCROPOPT -bot < $in",$tmp)) {
        my ($type,$width,$height2) = get_image_geometry($tmp);
        if($type && ($height - $height2) < 3 ) {
          # command succeeded and shaved less than 3 rows
          if($opt{debug}&&(-f $tmp)) {
            L2hos->Copy($tmp,$in);
            &increment_name($tmp);
          } elsif (-f $tmp) {
            L2hos->Rename($tmp,$in);
          }
          next;
        }
      }
      # MRO: this shouldn't be necessary: L2hos->Unlink($tmp);
      next; # go to next crop argument
    } # end switch on crop codes
#if @pipes@
    if($cmd) {
      # Continue command pipe
      $cmd .= "| $PNMCROP $croparg";
    } else {
      # start new pipe
      $cmd = "$PNMCROP $croparg< $in ";
    }
#else
    # Do the crop
    &do_cmd($in,$tmp,"$PNMCROP $croparg < $in") || return 0; # failure
#fi
  } # end cropping

#if !@have_geometry@ && @GSLANDSCAPE@ && @PNMFLIP@
  if($GSROTATE) {
#if @pipes@
    unless($cmd) {
      $cmd = "$PNMFLIP -$GS_UNROTATE < $in ";
    } else {
      $cmd .= "| $PNMFLIP -$GS_UNROTATE ";
    }
#else
    &do_cmd($in,$tmp,"$PNMFLIP -$GS_UNROTATE < $in ") || return 0;
#fi - pipes
  }
#fi - rotation

#if @PNMFLIP@
  if($opt{flip}) {
#if @pipes@
    unless($cmd) {
      $cmd = "$PNMFLIP -$opt{flip} < $in";
    } else {
      $cmd .= "| $PNMFLIP -$opt{flip} ";
    }
#else
    &do_cmd($in,$tmp,"$PNMFLIP -$opt{flip} < $in ") || return 0;
#fi
  }
#fi

#if @PNMFILE@ && @PBMMAKE@ && @PNMCAT@ # can justify
  if($RIGHT_JUSTIFY || $TOP_JUSTIFY || $CENTER || $SHORE_UP) {
#if @pipes@
    if($cmd) {
      # empty command pipe, we need the image's geometry
      &do_cmd($in,$tmp,$cmd);
      $cmd='';
    }
#fi

    # Get bitmap type and dimensions
    ($type,$width,$height) = &get_image_geometry($in);
    return 0 unless($type);

    my ($white_left,$white_right,$white_top,$white_bottom) = (0,0,0,0);

    if($RIGHT_JUSTIFY || $CENTER) {
      if($RIGHT_JUSTIFY) {
        $white_left = int($RIGHT_JUSTIFY-$width);
      } else { # CENTER
        $white_left = int(($CENTER-$width) / 2);
      }
      $white_left = 0 unless($white_left > 0);

      $width += $white_left;
    }

    if($TOP_JUSTIFY) {
      if($TOP_JUSTIFY =~ /^x([0-9.]+)/io) {
        $white_bottom = $1 * $height;
      } else {
        $white_bottom = $TOP_JUSTIFY - $height;
      }
      if($white_bottom > 0) {
        $white_bottom = int($white_bottom + 0.99); # round up
        $height += $white_bottom;
      } else {
        $white_bottom = 0;
      }
    }

    if($SHORE_UP =~ /(\d+)(d?)/ && $1) {
      # RRM: make height and width an exact multiple of $SHORE_UP
      my ($shoreup,$depth) = ($1,$2);
      my $extra = $height % $shoreup;
      if($depth) { # image needs depth, place half the extra space underneath
        my $bextra = int($extra/2);
        $white_bottom += $bextra;
        $white_top += $extra - $bextra;
      } else {
        $white_top += $extra;
      }

      $extra = $width % $shoreup;
      my $rextra = int($extra/2);
      $white_right += $rextra;
      $white_left += $extra - $rextra;
      $cmd = '';
    }

#unless @pipes@
  # create second temp filename for alignment images
  my $tmp2 = $in;
  $tmp2 =~ s/(\.[^.]*)?$/.tmp/;
#fi

  if($white_left) {
#if @pipes@
    if($cmd) {
      &do_cmd($in,$tmp,$cmd) || return 0;
    }
    # Start new command pipe
    $cmd = "$PBMMAKE -white $white_left 1 | $PNMCAT -white -lr - $in ";
#else
    &do_cmd_norename("$PBMMAKE -white $white_left 1", $tmp2) || return 0;
    &do_cmd($in,$tmp,"$PNMCAT -white -lr $tmp2 $in") || return 0;
    L2hos->Unlink($tmp2);
#fi
  }

  if($white_right) {
#if @pipes@
    if($cmd) {
      &do_cmd($in,$tmp,$cmd) || return 0;
    }
    # Start new command pipe
    $cmd = "$PBMMAKE -white $white_right 1 | $PNMCAT -white -lr $in - ";
#else
    &do_cmd_norename("$PBMMAKE -white $white_right 1", $tmp2) || return 0;
    &do_cmd($in,$tmp,"$PNMCAT -white -lr $in $tmp2") || return 0;
    L2hos->Unlink($tmp2);
#fi
  }

  if($white_top) {
#if @pipes@
    if($cmd) {
      &do_cmd($in,$tmp,$cmd) || return 0;
    }
    # Start new command pipe
    $cmd = "$PBMMAKE -white 1 $white_top | $PNMCAT -white -tb - $in ";
#else
    &do_cmd_norename("$PBMMAKE -white 1 $white_top", $tmp2) || return 0;
    &do_cmd($in,$tmp,"$PNMCAT -white -tb $tmp2 $in") || return 0;
    L2hos->Unlink($tmp2);
#fi
  }

  if($white_bottom) {
#if @pipes@
    if($cmd) {
      &do_cmd($in,$tmp,$cmd) || return 0;
    }
    # Start new command pipe
    $cmd = "$PBMMAKE -white 1 $white_bottom | $PNMCAT -white -tb $in - ";
#else
    &do_cmd_norename("$PBMMAKE -white 1 $white_bottom", $tmp2) || return 0;
    &do_cmd($in,$tmp,"$PNMCAT -white -tb $in $tmp2") || return 0;
    L2hos->Unlink($tmp2);
#fi
    }
  } # endif must_align
#fi # can justify

  my $pnmtoimg;
#if @IMAGE_TYPES@ =~ /gif/i
  if($opt{type} eq 'gif') {
    $pnmtoimg = $PPMTOGIF;
#if @gif_interlace@ eq 'netpbm'
    if($INTERLACE) {
      $pnmtoimg .= ' -interlace';
      }
#fi
#if @gif_trans@ eq 'netpbm'
    if($TRANSPARENT) {
      $pnmtoimg .= ' -trans ' . L2hos->quote($trans_color);
    }
#fi
  }
#fi - gif
#if @IMAGE_TYPES@ =~ /png/i
  if($opt{type} eq 'png') {
    $pnmtoimg = $PNMTOPNG;
    if($INTERLACE) {
      $pnmtoimg .= ' -interlace';
    }
    if($TRANSPARENT) {
      $trans_color = $TRANSPARENT_COLOR||'#d9d9d9'; # don't lookup rgb.txt
      #$trans_color = $TRANSPARENT_COLOR||'gray85';
      $pnmtoimg .= ' -trans ' . L2hos->quote($trans_color);
    }
  }
#fi - png
  unless($pnmtoimg) {
    print qq($prompt: Error: unknown image type "$opt{type}".\n);
    exit 2;
  }

#if @PPMQUANT@
#if @PNMFILE@
  unless($type) {
    ($type,$width,$height) = &get_image_geometry($in);
    return 0 unless($type);
  }
#fi
  # run ppmquant only on color/gray images
  if($reduce_color && (!$type || $type =~ /(ppm|pgm)/i)) {
#if @pipes@
    if($cmd) {
      $cmd .= "| $reduce_color "
    } else {
      $cmd = "$reduce_color < $in ";
    }
#else
    &do_cmd($in,$tmp,"$reduce_color < $in") || return 0;
#fi
  } else { $cmd = '' }
#fi # PPMQUANT

#if @pipes@
  if($cmd) {
    $cmd .= "| $pnmtoimg "
  } else {
    $cmd = "$pnmtoimg < $in ";
  }
  &do_cmd_norename($cmd,$out) || return 0;
#else
  &do_cmd_norename("$pnmtoimg < $in",$out) || return 0;
#fi
  print qq{$prompt: Written $out\n} unless($opt{quiet});

#if @gif_interlace@ eq 'giftool'
  if($opt{type} eq 'gif' && ($INTERLACE || $TRANSPARENT)) {
    $cmd = $GIFTOOL;
    if($INTERLACE) {
      $cmd .= ' -B -i';
    }
    if($TRANSPARENT) {
      $cmd .= ' -rgb ff,ff,ff';
    }
    print qq{Running "$cmd $out"\n} if $opt{debug};
    if(!&do_cmd_plain("$cmd $out") || !-s $out) {
      print qq{$prompt: Error: "$cmd $out" failed: $!\n};
      return 0;
    }
  }
#fi
#if @gif_trans@ eq 'giftrans'
  if($opt{type} eq 'gif' && $TRANSPARENT) {
    my $cmd = "$GIFTRANS -t " . L2hos->quote($trans_color) .
        ' -B ' . L2hos->quote('#bfbfbf') . ' ' .$out;
    &do_cmd($out,$tmp,$cmd) || return 0;
  }
#fi
  1;
}

sub banner {
  print "$prompt V$RELEASE (Revision $VERSION, Perl $])\n";
}

sub print_version {
  my $formats = join(',',@IMAGE_TYPES);
  print <<"EOM";
$prompt (Revision $VERSION, perl $]),
part of LaTeX2HTML Release V$RELEASE.

Supported output image format(s): $formats
EOM
  1;
}

sub print_help {
  L2hos->perldoc($SCRIPT);
  1;
}

sub print_usage {
  my $start  = 0;
  my $usage  = 'Usage: ';
  my $indent = '';

  print (@_, "\n") if @_;

#if @texlive@
  my $perldoc = "perldoc";
#else
  my $perldoc = '@PERLSCRIPTDIR@'.$dd."perldoc";
#fi
  my $script = $SCRIPT || $0;
  open(PIPE, "$perldoc -t $script |")
     || die "Fatal: can't open pipe: $!";
  while (<PIPE>)
  {
    if (/^\s*$/) {
      next;
    } elsif (/^SYNOPSIS/) {
      $start = 1;
    } elsif (/^\w/) {
      $start = 0;
    } elsif ($start == 1) {
      ($indent) = /^(\s*)/;
      s/^$indent/$usage/;
      $usage =~ s/./ /g;
      $start = 2;
      print $_;
    } elsif ($start == 2) {
      s/^$indent/$usage/;
      print $_;
    }
  }
  close PIPE;
  1;
}

sub do_cmd {
  my ($in,$tmp,$cmd) = @_;
  
  print qq{Running "$cmd > $tmp"\n} if($opt{debug});
  my $stat = system("$cmd > $tmp");
  if($stat) { # error
    print qq{$prompt: Error: "$cmd > $tmp" failed: $!\n};
    return 0; # failure
  }
  elsif(!-s $tmp) { # does not exist or zero size
    print qq{$prompt: Error: "$cmd > $tmp" produced empty file\n};
    L2hos->Unlink($tmp) if(-e $tmp);
    return 0; # failure
  }
  if($opt{debug}) {
    # increase the temporary filename by 1
    # this uses perl's magic autoincrement
    &increment_name($_[1]);
    return L2hos->Copy($tmp,$in);
  } elsif(!L2hos->Rename($tmp,$in)) {
     print qq{$prompt: Error: rename of "$tmp" to "$in" failed: $!\n};
     return 0; # failure
  }
  1;
}

sub do_cmd_norename {
  my ($cmd,$out) = @_;
  
  print qq{Running "$cmd > $out"\n} if($opt{debug});
  my $stat = system("$cmd > $out");
  if($stat) { # error
    print qq{$prompt: Error: "$cmd > $out" failed: $!\n};
    return 0; # failure
  }
  elsif(!-s $out) { # does not exist or zero size
    print qq{$prompt: Error: "$cmd > $out" produced empty file\n};
    L2hos->Unlink($out) if(-e $out);
    return 0; # failure
  }
  1;
}

sub do_cmd_plain {
  my ($cmd) = @_;
  
  print qq{Running "$cmd"\n} if($opt{debug});
  my $stat = system($cmd);
  if($stat) { # error
    print qq{$prompt: Error: "$cmd" failed: $!\n};
    return 0; # failure
  }
  1;
}

sub get_image_geometry {
  my ($pnmfile) = @_;

  my ($type,$width,$height);
  my $out = `$PNMFILE $pnmfile`;
  if($? || $out =~ /(P[BGP]M)[^0-9]*(\d+)\s*by\s*(\d+)/i) {
    $type = $1;
    $width = $2;
    $height = $3;
    print qq{Image "$pnmfile" is $type, ${width}x$height\n} if($opt{debug});
  } else {
    print "$prompt: Error: Could not determine image size: $out\n";
    return undef;
  }
  ($type,$width,$height);
}

# push the number in the suffix up one notch
sub increment_name {
  $_[0] =~ s/(\d+)$/$a=$1;++$a/e;
}

__DATA__

=head1 EXAMPLES

=over 4

=item C<pstoimg foo.ps>

Convert the first page of foo.ps to the default bitmap type.

=item C<pstoimg -type png -crop a -trans -interlace foo.ps>

Same as above, but force png output and crop all the whitespace
around the image and make the color white transparent and
generate an interlaced bitmap.

=item C<pstoimg -multi -out bar -type gif -crop a foo.ps>

Consider foo.ps a multiple page PostScript file and create output
files bar1.gif, bar2.gif, etc.

=back

=head1 ENVIRONMENT

=over 4

=item DENSITY, DEPTH, DEBUG, DISCARD

See B<-density>, B<-depth>, B<-debug>, B<-discard>, respectively.

=item GS_LIB

This variable is set to the path(s) where Ghostscript libraries have
been found on this system during configuration, but only if the built-in
paths are not correct. This fixes the problem of relocation that is quite
common on Win32 installations. This behavior can be overridden by
setting GS_LIB manually before starting pstoimg.

=item LATEX2HTMLDIR

The directory where the LaTeX2HTML library and perl modules are found.
Defaults to "@LATEX2HTMLDIR@" on this installation.

=item OUTFILE

Setting this has the same effect as specifying B<-out>. Please do not rely
on this feature any more, it will disappear from the next releases!

=item PAPERSIZE

The papersize to use by Ghostscript to render the image. pstoimg tries
hard to optimize for rendering on the smallest possible bitmap size.
Still this option is there to enable tuning by hand, although it is
deprecated. If pstoimg finds a better setting, this parameter is ignored.

=item SCALE

See the discussion of B<-scale>.

=item TMP and TEMP

Unless overridden by B<-tmp>, these variables denote a directory where
to store temporary files. TMP is considered first, then TEMP.

=back

=head1 SEE ALSO

gs, pnmcrop, pnmquant, pbmmake, pnmcat, pnmfile, pnmflip, ppmtogif,
pnmtopng, giftool, giftrans.

=head1 NOTES

Several people have suggested to use ImageMagick's convert instead of
pstoimg. A few comments on this: convert uses (of course) Ghostscript 
for conversion of PostScript to bitmap, so one still needs gs. And
for the special requirements of LaTeX2HTML convert's features are not
sufficient. The ImageMagick toolset has everything in place, but it
has some overhead that can prove killing when processing some 100 
images. pstoimg only does what it really has to, so it should be
quite efficient. Don't get me wrong - I like ImageMagick, but not in
the context of LaTeX2HTML.

=head1 CAVEATS

This utility is automatically configured and built to work on the
local setup. If this setup changes (e.g. some of the external commands
are moved), the script has be be reconfigured.

Despite the portability of perl, a pstoimg configured on UNIX will
probably not work on Win32 and vice versa.

=head1 BUGS

This is a major enhancement release, so there may be a few bugs. As
the user inteface changed a bit, some of your tools that were using
pstoimg may not work any more. 

Please report bugs to latex2html@tug.org, stating the (debug) output
of pstoimg, your perl version and the versions of the external tools.
Best is to include the cfgcache.pm file from the configuration procedure.

=head1 AUTHOR

Marek Rouchal E<lt>marek@saftsack.fs.uni-bayreuth.deE<gt>

=head1 HISTORY

This script went through a long evolution, beginning with a modification
of Doug Crabill's E<lt>dgc@cs.purdue.eduE<gt> ps2epsi script.
The first perl version was done by Nikos Drakos <nikos@cbl.leeds.ac.uk>.
It was gradually improved by numerous LaTeX2HTML developers:
Ross Moore <ross@maths.mq.edu.au>, Jens Lippmann 
<lippmann@rbg.informatik.tu-darmstadt.de> and others (sorry for not
mentioning everyone and thanks for your contributions).

=cut