about summary refs log tree commit diff
path: root/generator/pamstereogram.c
blob: 4bc1ea92d6098aa29f2d3166b4579b46e8b51385 (plain) (blame)
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
/* ----------------------------------------------------------------------
 *
 * Create a single image stereogram from a height map.
 * by Scott Pakin <scott+pbm@pakin.org>
 * Adapted to Netbpm conventions by Bryan Henderson.
 * Revised by Scott Pakin.
 *
 * The core of this program is a simple adaptation of the code in
 * "Displaying 3D Images: Algorithms for Single Image Random Dot
 * Stereograms" by Harold W. Thimbleby, Stuart Inglis, and Ian
 * H. Witten in IEEE Computer, 27(10):38-48, October 1994 plus some
 * enhancements presented in "Stereograms: Technical Details" by
 * W. A. Steer at http://www.techmind.org/stereo/stech.html.  See
 * those references for a thorough explanation of what's going on
 * here.
 *
 * ----------------------------------------------------------------------
 *
 * Copyright (C) 2006-2021 Scott Pakin <scott+pbm@pakin.org>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ----------------------------------------------------------------------
 */

#define _ISOC99_SOURCE  /* Make sure strtof() is in <stdlib.h> */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <limits.h>
#include <assert.h>

#include "pm_config.h"
#include "pm_c_util.h"
#include "mallocvar.h"
#include "nstring.h"
#include "rand.h"
#include "shhopt.h"
#include "pam.h"


enum OutputType {OUTPUT_BW, OUTPUT_GRAYSCALE, OUTPUT_COLOR};

/* ---------------------------------------------------------------------- */

struct cmdlineInfo {
    /* All the information the user supplied in the command line,
       in a form easy for the program to use.
    */
    const char * inputFilespec;  /* '-' if stdin */
    unsigned int verbose;        /* -verbose option */
    unsigned int crosseyed;      /* -crosseyed option */
    unsigned int makemask;       /* -makemask option */
    unsigned int dpi;            /* -dpi option */
    float        eyesep;         /* -eyesep option */
    float        depth;          /* -depth option */
    unsigned int maxvalSpec;     /* -maxval option count */
    unsigned int maxval;         /* -maxval option value */
    unsigned int guidetop;       /* -guidetop option count */
    unsigned int guidebottom;    /* -guidebottom option count */
    unsigned int guidesize;      /* -guidesize option value */
    unsigned int magnifypat;     /* -magnifypat option */
    int xshift;                  /* -xshift option */
    int yshift;                  /* -yshift option */
    int yfillshift;              /* -yfillshift option */
    const char * patfile;        /* -patfile option.  Null if none */
    const char * texfile;        /* -texfile option.  Null if none */
    const char * bgcolor;        /* -bgcolor option */
    unsigned int smoothing;      /* -smoothing option */
    unsigned int randomseed;     /* -randomseed option */
    unsigned int randomseedSpec; /* -randomseed option count */
    enum OutputType outputType;  /* Type of output file */
    unsigned int xbegin;         /* -xbegin option */
    unsigned int xbeginSpec;     /* -xbegin option count */
    unsigned int tileable;       /* -tileable option */
};



static void
parseNearFarPlanes(const char ** const nearFarPlanes,
                   float *       const nearPlaneP,
                   float *       const farPlaneP) {
/*----------------------------------------------------------------------------
  Parse nearFarPlanes option value into exactly two positive numbers
-----------------------------------------------------------------------------*/
    float nearPlane, farPlane;

    if (nearFarPlanes == NULL || nearFarPlanes[0] == NULL ||
        nearFarPlanes[1] == NULL || nearFarPlanes[2] != NULL)
        pm_error("-planes requires exactly two positive numbers");

    errno = 0;
    nearPlane = strtof(nearFarPlanes[0], NULL);
    if (errno != 0 || nearPlane <= 0.0)
        pm_error("-planes requires exactly two positive numbers");

    farPlane = strtof(nearFarPlanes[1], NULL);
    if (errno != 0 || farPlane <= 0.0)
        pm_error("-planes requires exactly two positive numbers");

    if (nearPlane >= farPlane)
        pm_error("-planes requires the near-plane value "
                 "to be less than the far-plane value");

    *nearPlaneP = nearPlane;
    *farPlaneP  = farPlane;
}



static void
parseCommandLine(int                  argc,
                 const char **        argv,
                 struct cmdlineInfo * cmdlineP ) {
/*----------------------------------------------------------------------------
   Parse program command line described in Unix standard form by argc
   and argv.  Return the information in the options as *cmdlineP.

   If command line is internally inconsistent (invalid options, etc.),
   issue error message to stderr and abort program.

   Note that the strings we return are stored in the storage that
   was passed to us as the argv array.  We also trash *argv.
-----------------------------------------------------------------------------*/
    optEntry *option_def;
        /* Instructions to pm_optParseOptions3 on how to parse our options.
         */
    optStruct3 opt;

    unsigned int option_def_index;

    unsigned int patfileSpec, texfileSpec, dpiSpec, eyesepSpec, depthSpec,
        guidesizeSpec, magnifypatSpec, xshiftSpec, yshiftSpec, yfillshiftSpec,
        bgcolorSpec, smoothingSpec, planesSpec;

    unsigned int blackandwhite, grayscale, color;
    const char ** planes;

    MALLOCARRAY_NOFAIL(option_def, 100);

    option_def_index = 0;   /* incremented by OPTENT3 */
    OPTENT3(0, "verbose",         OPT_FLAG,   NULL,
            (unsigned int *)&cmdlineP->verbose,       0);
    OPTENT3(0, "crosseyed",       OPT_FLAG,   NULL,
            &cmdlineP->crosseyed,     0);
    OPTENT3(0, "makemask",        OPT_FLAG,   NULL,
            &cmdlineP->makemask,      0);
    OPTENT3(0, "blackandwhite",   OPT_FLAG,   NULL,
            &blackandwhite,           0);
    OPTENT3(0, "grayscale",       OPT_FLAG,   NULL,
            &grayscale,               0);
    OPTENT3(0, "color",           OPT_FLAG,   NULL,
            &color,                   0);
    OPTENT3(0, "dpi",             OPT_UINT,   &cmdlineP->dpi,
            &dpiSpec,                 0);
    OPTENT3(0, "eyesep",          OPT_FLOAT,  &cmdlineP->eyesep,
            &eyesepSpec,              0);
    OPTENT3(0, "depth",           OPT_FLOAT,  &cmdlineP->depth,
            &depthSpec,               0);
    OPTENT3(0, "maxval",          OPT_UINT,   &cmdlineP->maxval,
            &cmdlineP->maxvalSpec,    0);
    OPTENT3(0, "guidetop",        OPT_FLAG,   NULL,
            &cmdlineP->guidetop,      0);
    OPTENT3(0, "guidebottom",     OPT_FLAG,   NULL,
            &cmdlineP->guidebottom,   0);
    OPTENT3(0, "guidesize",       OPT_UINT,   &cmdlineP->guidesize,
            &guidesizeSpec,           0);
    OPTENT3(0, "magnifypat",      OPT_UINT,   &cmdlineP->magnifypat,
            &magnifypatSpec,          0);
    OPTENT3(0, "xshift",          OPT_INT,    &cmdlineP->xshift,
            &xshiftSpec,              0);
    OPTENT3(0, "yshift",          OPT_INT,    &cmdlineP->yshift,
            &yshiftSpec,              0);
    OPTENT3(0, "yfillshift",      OPT_INT,    &cmdlineP->yfillshift,
            &yfillshiftSpec,          0);
    OPTENT3(0, "patfile",         OPT_STRING, &cmdlineP->patfile,
            &patfileSpec,             0);
    OPTENT3(0, "texfile",         OPT_STRING, &cmdlineP->texfile,
            &texfileSpec,             0);
    OPTENT3(0, "bgcolor",         OPT_STRING, &cmdlineP->bgcolor,
            &bgcolorSpec,             0);
    OPTENT3(0, "randomseed",      OPT_UINT,   &cmdlineP->randomseed,
            &cmdlineP->randomseedSpec, 0);
    OPTENT3(0, "smoothing",       OPT_UINT,   &cmdlineP->smoothing,
            &smoothingSpec,           0);
    OPTENT3(0, "planes",          OPT_STRINGLIST, &planes,
            &planesSpec,              0);
    OPTENT3(0, "xbegin",          OPT_UINT,   &cmdlineP->xbegin,
            &cmdlineP->xbeginSpec,    0);
    OPTENT3(0, "tileable",        OPT_FLAG,   NULL,
            (unsigned int *)&cmdlineP->tileable,  0);

    opt.opt_table = option_def;
    opt.short_allowed = FALSE;  /* We have no short (old-fashioned) options */
    opt.allowNegNum = FALSE;  /* We have no parms that are negative numbers */

    pm_optParseOptions3(&argc, (char **)argv, opt, sizeof(opt), 0);
        /* Uses and sets argc, argv, and some of *cmdlineP and others. */

    if (blackandwhite + grayscale + color == 0)
        cmdlineP->outputType = OUTPUT_BW;
    else if (blackandwhite + grayscale + color > 1)
        pm_error("You may specify only one of -blackandwhite, -grayscale, "
                 "and -color");
    else {
        if (blackandwhite)
            cmdlineP->outputType = OUTPUT_BW;
        else if (grayscale)
            cmdlineP->outputType = OUTPUT_GRAYSCALE;
        else {
            assert(color);
            cmdlineP->outputType = OUTPUT_COLOR;
        }
    }
    if (!patfileSpec)
        cmdlineP->patfile = NULL;
    if (!texfileSpec)
        cmdlineP->texfile = NULL;
    if (!bgcolorSpec)
        cmdlineP->bgcolor = NULL;
    if (!smoothingSpec)
        cmdlineP->smoothing = 0;

    if (!dpiSpec)
        cmdlineP->dpi = 100;
    else if (cmdlineP->dpi < 1)
        pm_error("The argument to -dpi must be a positive integer");

    if (!eyesepSpec)
        cmdlineP->eyesep = 2.56;
    else if (cmdlineP->eyesep <= 0.0)
        pm_error("The argument to -eyesep must be a positive number");

    if (!depthSpec)
        cmdlineP->depth = (1.0/3.0);
    else if (cmdlineP->depth < 0.0 || cmdlineP->depth > 1.0)
        pm_error("The argument to -depth must be a number from 0.0 to 1.0");

    if (cmdlineP->maxvalSpec) {
        if (cmdlineP->maxval < 1)
            pm_error("-maxval must be at least 1");
        else if (cmdlineP->maxval > PNM_OVERALLMAXVAL)
            pm_error("-maxval must be at most %u.  You specified %u",
                     PNM_OVERALLMAXVAL, cmdlineP->maxval);
    }
    if (bgcolorSpec && !texfileSpec)
        pm_message("warning: -bgcolor has no effect "
                   "except in conjunction with -texfile");

    if (guidesizeSpec && !(cmdlineP->guidetop || cmdlineP->guidebottom))
        pm_error("-guidesize has no meaning "
                 "without -guidetop or -guidebottom");

    if (!guidesizeSpec)
        cmdlineP->guidesize = 20;

    if (!magnifypatSpec)
        cmdlineP->magnifypat = 1;
    else if (cmdlineP->magnifypat < 1)
        pm_error("The argument to -magnifypat must be a positive integer");

    if (!xshiftSpec)
        cmdlineP->xshift = 0;
    if (!yshiftSpec)
        cmdlineP->yshift = 0;
    if (!yfillshiftSpec)
        cmdlineP->yfillshift = 0;

    if (xshiftSpec && !cmdlineP->patfile)
        pm_error("-xshift is valid only with -patfile");
    if (yshiftSpec && !cmdlineP->patfile)
        pm_error("-yshift is valid only with -patfile");

    if (cmdlineP->makemask && cmdlineP->patfile)
        pm_error("You may not specify both -makemask and -patfile");

    if (cmdlineP->tileable && cmdlineP->xbeginSpec)
        pm_error("You may not specify both -tileable and -xbegin");
    if (cmdlineP->tileable && !cmdlineP->patfile)
        pm_error("-tileable is valid only with -patfile");

    if (cmdlineP->patfile && blackandwhite)
        pm_error("-blackandwhite is not valid with -patfile");
    if (cmdlineP->patfile && grayscale)
        pm_error("-grayscale is not valid with -patfile");
    if (cmdlineP->patfile && color)
        pm_error("-color is not valid with -patfile");
    if (cmdlineP->patfile && cmdlineP->maxvalSpec)
        pm_error("-maxval is not valid with -patfile");

    if (cmdlineP->texfile && blackandwhite)
        pm_error("-blackandwhite is not valid with -texfile");
    if (cmdlineP->texfile && grayscale)
        pm_error("-grayscale is not valid with -texfile");
    if (cmdlineP->texfile && color)
        pm_error("-color is not valid with -texfile");
    if (cmdlineP->texfile && cmdlineP->maxvalSpec)
        pm_error("-maxval is not valid with -texfile");
    if (planesSpec && eyesepSpec)
        pm_error("-planes is not valid with -eyesep");
    if (planesSpec && depthSpec)
        pm_error("-planes is not valid with -depth");

    if (planesSpec) {
        float nearPlane, farPlane;
        parseNearFarPlanes(planes, &nearPlane, &farPlane);
        cmdlineP->eyesep = 2.0*farPlane/cmdlineP->dpi;
        cmdlineP->depth = 2.0*(farPlane-nearPlane) / (2.0*farPlane-nearPlane);
    }

    if (argc-1 < 1)
        cmdlineP->inputFilespec = "-";
    else if (argc-1 == 1)
        cmdlineP->inputFilespec = argv[1];
    else
        pm_error("Too many non-option arguments: %d.  Only argument is "
                 "input file name", argc-1);
}



static unsigned int
separation(double             const dist,
           double             const eyesep,
           unsigned int       const dpi,
           double             const dof /* depth of field */
    ) {
/*----------------------------------------------------------------------------
  Return a separation in pixels which corresponds to a 3-D distance
  between the viewer's eyes and a point on an object.
-----------------------------------------------------------------------------*/
    unsigned int const pixelEyesep = ROUNDU(eyesep * dpi);

    return ROUNDU((1.0 - dof * dist) * pixelEyesep / (2.0 - dof * dist));
}



static void
reportImageParameters(const char * const fileDesc,
                      const struct pam * const pamP) {

    pm_message("%s: tuple type '%s', %d wide x %d high x %d deep, maxval %lu",
               fileDesc, pamP->tuple_type, pamP->width, pamP->height,
               pamP->depth, pamP->maxval);
}



/*----------------------------------------------------------------------------
   Background generators
-----------------------------------------------------------------------------*/

struct outGenerator;

typedef tuple coord2Color(struct outGenerator *, int, int);
    /* A type to use for functions that map a 2-D coordinate to a color. */
typedef void outGenStateTerm(struct outGenerator *);

typedef struct {
    struct pam   pam;
    tuple **     imageData;
    tuple        bgColor;
    bool         replaceBgColor;
        /* replace background color with pattern color */
    unsigned int smoothing;
        /* Number of background-smoothing iterations to perform */
} texState;

typedef struct outGenerator {
    struct pam        pam;
    coord2Color *     getTuple;
        /* Map from a height-map (x,y) coordinate to a tuple */
    outGenStateTerm * terminateState;
    void *            stateP;
    texState *        textureP;
        /* Mapped-texture part of the state of operation.  Null
           means we are doing an ordinary stereogram instead of a
           mapped-texture one.
        */
} outGenerator;



struct RandomState {
    /* The state of a randomColor generator. */
    unsigned int magnifypat;
    tuple *      currentRow;
    unsigned int prevy;
    struct pm_randSt * randStP;
};


#ifndef LITERAL_FN_DEF_MATCH
static coord2Color randomColor;
#endif

static tuple
randomColor(outGenerator * const outGenP,
            int            const x,
            int            const y) {
/*----------------------------------------------------------------------------
   Return a random RGB value.
-----------------------------------------------------------------------------*/
    struct RandomState * const stateP = outGenP->stateP;

    /* Every time we start a new row, we select a new sequence of random
       colors.
    */
    if (y/stateP->magnifypat != stateP->prevy/stateP->magnifypat) {
        unsigned int const modulus = outGenP->pam.maxval + 1;
        int col;

        for (col = 0; col < outGenP->pam.width; ++col) {
            tuple const thisTuple = stateP->currentRow[col];

            unsigned int plane;

            for (plane = 0; plane < outGenP->pam.depth; ++plane) {
                unsigned int const randval = pm_rand(stateP->randStP);
                thisTuple[plane] = randval % modulus;
            }
        }
    }

    /* Return the appropriate column from the pregenerated color row. */
    stateP->prevy = y;
    return stateP->currentRow[x/stateP->magnifypat];
}



#ifndef LITERAL_FN_DEF_MATCH
static outGenStateTerm termRandomColor;
#endif

static void
termRandomColor(outGenerator * const outGenP) {

    struct RandomState * const stateP = outGenP->stateP;

    pnm_freepamrow(stateP->currentRow);

    pm_randterm(stateP->randStP);

    free(stateP->randStP);
}



static void
initRandomColor(outGenerator *     const outGenP,
                const struct pam * const inPamP,
                struct cmdlineInfo const cmdline) {

    struct RandomState * stateP;

    outGenP->pam.format      = PAM_FORMAT;
    outGenP->pam.plainformat = 0;

    switch (cmdline.outputType) {
    case OUTPUT_BW:
        strcpy(outGenP->pam.tuple_type, PAM_PBM_TUPLETYPE);
        outGenP->pam.maxval = 1;
        outGenP->pam.depth = 1;
        break;
    case OUTPUT_GRAYSCALE:
        strcpy(outGenP->pam.tuple_type, PAM_PGM_TUPLETYPE);
        outGenP->pam.maxval =
            cmdline.maxvalSpec ? cmdline.maxval : inPamP->maxval;
        outGenP->pam.depth = 1;
        break;
    case OUTPUT_COLOR:
        strcpy(outGenP->pam.tuple_type, PAM_PPM_TUPLETYPE);
        outGenP->pam.maxval =
            cmdline.maxvalSpec ? cmdline.maxval : inPamP->maxval;
        outGenP->pam.depth = 3;
        break;
    }

    MALLOCVAR_NOFAIL(stateP);

    stateP->currentRow = pnm_allocpamrow(&outGenP->pam);
    stateP->magnifypat = cmdline.magnifypat;
    stateP->prevy      = (unsigned int)(-cmdline.magnifypat);

    MALLOCVAR_NOFAIL(stateP->randStP);
    pm_randinit(stateP->randStP);
    pm_srand2(stateP->randStP, cmdline.randomseedSpec, cmdline.randomseed);

    outGenP->stateP         = stateP;
    outGenP->getTuple       = &randomColor;
    outGenP->terminateState = &termRandomColor;
}



struct patternPixelState {
    /* This is the state of a patternPixel generator.*/
    struct pam   patPam;     /* Descriptor of pattern image */
    tuple **     patTuples;  /* Entire image read from the pattern file */
    int xshift;
    int yshift;
    unsigned int magnifypat;
};



#ifndef LITERAL_FN_DEF_MATCH
static coord2Color patternPixel;
#endif

static tuple
patternPixel(outGenerator * const outGenP,
             int            const x,
             int            const y) {
/*----------------------------------------------------------------------------
  Return a pixel from the pattern file.
-----------------------------------------------------------------------------*/
    struct patternPixelState * const stateP = outGenP->stateP;
    struct pam * const patPamP = &stateP->patPam;

    int patx, paty;

    paty = ((y - stateP->yshift) / stateP->magnifypat) % patPamP->height;

    if (paty < 0)
        paty += patPamP->height;

    patx = ((x - stateP->xshift) / stateP->magnifypat) % patPamP->width;

    if (patx < 0)
        patx += patPamP->width;

    return stateP->patTuples[paty][patx];
}



#ifndef LITERAL_FN_DEF_MATCH
static outGenStateTerm termPatternPixel;
#endif

static void
termPatternPixel(outGenerator * const outGenP) {

    struct patternPixelState * const stateP = outGenP->stateP;

    pnm_freepamarray(stateP->patTuples, &stateP->patPam);
}



static void
initPatternPixel(outGenerator *     const outGenP,
                 struct cmdlineInfo const cmdline) {
/*----------------------------------------------------------------------------
   Initialize parts of output generator *outGenP that are based on the
   supplied pattern file, assuming there is one.
-----------------------------------------------------------------------------*/
    struct patternPixelState * stateP;
    FILE * patternFileP;

    MALLOCVAR_NOFAIL(stateP);

    assert(cmdline.patfile);

    patternFileP = pm_openr(cmdline.patfile);

    stateP->patTuples =
        pnm_readpam(patternFileP,
                    &stateP->patPam, PAM_STRUCT_SIZE(tuple_type));

    pm_close(patternFileP);

    stateP->xshift     = cmdline.xshift;
    stateP->yshift     = cmdline.yshift;
    stateP->magnifypat = cmdline.magnifypat;

    outGenP->stateP          = stateP;
    outGenP->getTuple        = &patternPixel;
    outGenP->terminateState  = &termPatternPixel;
    outGenP->pam.format      = stateP->patPam.format;
    outGenP->pam.plainformat = stateP->patPam.plainformat;
    outGenP->pam.depth       = stateP->patPam.depth;
    outGenP->pam.maxval      = stateP->patPam.maxval;
    strcpy(outGenP->pam.tuple_type, stateP->patPam.tuple_type);

    if (cmdline.verbose)
        reportImageParameters("Pattern file", &stateP->patPam);
}



static void
readTextureImage(struct cmdlineInfo const cmdline,
                 const struct pam * const inpamP,
                 const struct pam * const outpamP,
                 texState **        const texturePP) {

    FILE *       textureFileP;
    texState *   textureP;
    struct pam * texPamP;

    MALLOCVAR_NOFAIL(textureP);
    texPamP = &textureP->pam;

    textureFileP = pm_openr(cmdline.texfile);
    textureP->imageData =
        pnm_readpam(textureFileP, texPamP, PAM_STRUCT_SIZE(tuple_type));
    pm_close(textureFileP);

    if (cmdline.bgcolor)
        textureP->bgColor =
            pnm_parsecolor(cmdline.bgcolor, texPamP->maxval);
    else
        textureP->bgColor =
            pnm_backgroundtuple(texPamP, textureP->imageData);
    textureP->replaceBgColor = (cmdline.patfile != NULL);
    textureP->smoothing = cmdline.smoothing;

    if (cmdline.verbose) {
        const char * const colorname =
            pnm_colorname(texPamP, textureP->bgColor, 1);

        reportImageParameters("Texture file", texPamP);
        if (cmdline.bgcolor && strcmp(colorname, cmdline.bgcolor))
            pm_message("Texture background color: %s (%s)",
                       cmdline.bgcolor, colorname);
        else
            pm_message("Texture background color: %s", colorname);
        pm_strfree(colorname);
    }

    if (texPamP->width != inpamP->width || texPamP->height != inpamP->height)
        pm_error("The texture image must have the same width and height "
                 "as the input image");
    if (cmdline.patfile &&
        (!streq(texPamP->tuple_type, outpamP->tuple_type) ||
         texPamP->maxval != outpamP->maxval))
        pm_error("The texture image must be of the same tuple type "
                 "and maxval as the pattern image");

    textureP->pam.file = outpamP->file;

    *texturePP = textureP;
}



static unsigned int
totalGuideHeight(struct cmdlineInfo const cmdline) {

    /* Each pair of guides is cmdline.guidesize high, and we add that much
       white above and below as well, so the total vertical space is three
       times cmdline.giudesize.
    */

    return
        (cmdline.guidetop ? 3 * cmdline.guidesize : 0) +
        (cmdline.guidebottom ? 3 * cmdline.guidesize : 0);
}



static void
createoutputGenerator(struct cmdlineInfo const cmdline,
                      const struct pam * const inPamP,
                      outGenerator **    const outputGeneratorPP) {

    outGenerator * outGenP;

    MALLOCVAR_NOFAIL(outGenP);

    outGenP->pam.size   = sizeof(struct pam);
    outGenP->pam.len    = PAM_STRUCT_SIZE(tuple_type);
    outGenP->pam.file   = stdout;
    outGenP->pam.height = inPamP->height + totalGuideHeight(cmdline);
    outGenP->pam.width  = inPamP->width;

    if (cmdline.patfile) {
        /* Background pixels should come from the pattern file. */

        initPatternPixel(outGenP, cmdline);
    } else {
        /* Background pixels should be generated randomly */

        initRandomColor(outGenP, inPamP, cmdline);
    }

    outGenP->pam.bytes_per_sample = pnm_bytespersample(outGenP->pam.maxval);

    if (cmdline.texfile) {
        readTextureImage(cmdline, inPamP, &outGenP->pam, &outGenP->textureP);
        outGenP->pam = outGenP->textureP->pam;
    } else
        outGenP->textureP = NULL;

    *outputGeneratorPP = outGenP;
}



static void
destroyoutputGenerator(outGenerator * const outputGeneratorP) {

    outputGeneratorP->terminateState(outputGeneratorP);
    free(outputGeneratorP);
}


/* End of background generators */

/* ---------------------------------------------------------------------- */


static void
makeWhiteRow(const struct pam * const pamP,
             tuple *            const tuplerow) {

    unsigned int col;

    for (col = 0; col < pamP->width; ++col) {
        unsigned int plane;
        for (plane = 0; plane < pamP->depth; ++plane)
            tuplerow[col][plane] = pamP->maxval;
    }
}



static void
writeRowCopies(const struct pam *  const outPamP,
               const tuple *       const outrow,
               unsigned int        const copyCount) {

    unsigned int i;

    for (i = 0; i < copyCount; ++i)
        pnm_writepamrow(outPamP, outrow);
}



static void
writeWhiteRows(const struct pam * const outPamP,
               unsigned int       const count) {

    tuple * outrow;             /* One row of output data */

    outrow = pnm_allocpamrow(outPamP);

    makeWhiteRow(outPamP, outrow);

    writeRowCopies(outPamP, outrow, count);

    pnm_freerow(outrow);
}



static void
drawguides(unsigned int       const guidesize,
           const struct pam * const outPamP,
           double             const eyesep,
           unsigned int       const dpi,
           double             const depthOfField) {
/*----------------------------------------------------------------------------
   Draw a pair of guide boxes, left and right.
-----------------------------------------------------------------------------*/
    unsigned int const far = separation(0, eyesep, dpi, depthOfField);
        /* Space between the two guide boxes. */
    unsigned int const width = outPamP->width;  /* Width of the output image */

    tuple * outrow;             /* One row of output data */
    tuple blackTuple;
    unsigned int col;

    pnm_createBlackTuple(outPamP, &blackTuple);

    outrow = pnm_allocpamrow(outPamP);

    /* Put some white rows before the guides */
    writeWhiteRows(outPamP, guidesize);

    /* Initialize the row buffer to white */
    makeWhiteRow(outPamP, outrow);

    if (far > width + guidesize)
        pm_message("warning: the guide boxes are completely out of bounds "
                   "at %u DPI", dpi);
    else {
        unsigned int leftBeg, leftEnd, rightBeg, rightEnd;

        assert(far <= width + guidesize);
        leftEnd  = (width - far + guidesize)/2;
        assert(guidesize <= width + far);
        rightBeg = (width + far - guidesize)/2;

        if (far + guidesize > width) {
            pm_message("warning: the guide boxes are partially out of bounds "
                       "at %u DPI", dpi);

            leftBeg  = 0;
            rightEnd = width;
        } else {
            assert(far + guidesize <= width);
            leftBeg  = (width - far - guidesize)/2;
            rightEnd = (width + far + guidesize)/2;
        }

        /* Draw the left guide black in the buffer */
        assert(leftEnd < outPamP->width);
        for (col = leftBeg; col < leftEnd; ++col)
            pnm_assigntuple(outPamP, outrow[col], blackTuple);

        /* Draw the right guide black in the buffer */
        assert(rightEnd <= outPamP->width);
        for (col = rightBeg; col < rightEnd; ++col)
            pnm_assigntuple(outPamP, outrow[col], blackTuple);
    }
    /* Write out the guide rows */

    writeRowCopies(outPamP, outrow, guidesize);

    /* Put some white rows after the guides */
    writeWhiteRows(outPamP, guidesize);

    pnm_freerow(outrow);
}



static void
makeStereoRow(const struct pam * const inPamP,
              tuple *            const inRow,
              unsigned int *     const sameL,
              unsigned int *     const sameR,
              double             const depthOfField,
              double             const eyesep,
              unsigned int       const dpi,
              unsigned int       const optWidth,
              unsigned int       const smoothing) {
/*----------------------------------------------------------------------------
  Given a row of the depth map inRow[], compute the sameL and sameR arrays,
  which indicate for each pixel which pixel to its left and right it should be
  colored the same as.
-----------------------------------------------------------------------------*/

#define Z(X) (inRow[X][0]/(double)inPamP->maxval)

    unsigned int col;

    for (col = 0; col < inPamP->width; ++col) {
        sameL[col] = col;
        sameR[col] = col;
    }

    for (col = 0; col < inPamP->width; ++col) {
        unsigned int const sep = separation(Z(col), eyesep, dpi, depthOfField);
        int const left = col - sep/2;
        int const right = left + sep;

        if (left >= 0 && right < inPamP->width) {
            bool isVisible;

            if (sameL[right] != right) {
                /* Right point already linked */
                if (sameL[right] < left) {
                    /* Deeper than current */
                    sameR[sameL[right]] = sameL[right];  /* Break old links. */
                    sameL[right] = right;
                    isVisible = TRUE;
                } else
                    isVisible = FALSE;
            } else
                isVisible = TRUE;

            if (sameR[left] != left) {
                /* Left point already linked */
                if (sameR[left] > right) {
                    /* Deeper than current */
                    sameL[sameR[left]] = sameR[left];  /* Break old links. */
                    sameR[left] = left;
                    isVisible = TRUE;
                } else
                    isVisible = FALSE;
            } else
                isVisible = TRUE;

            if (isVisible) {
                /* Make a link. */
                sameL[right] = left;
                sameR[left] = right;
            }
        }
    }

    /* If smoothing is enabled, replace each non-duplicate pixel with
       the pixel adjacent to its right neighbor.
    */
    if (smoothing > 0) {
        int const baseCol = inPamP->width - optWidth - 1;

        int col;

        for (col = inPamP->width - 1; col >= 0; --col)
            sameR[col] = sameR[sameR[col]];
        for (col = baseCol; col >= 0; --col) {
            if (sameR[col] == col)
                sameR[col] = sameR[col+1] - 1;
        }
    }
}



static void
makeMaskRow(const struct pam *   const outPamP,
            unsigned int         const xbegin,
            const unsigned int * const sameL,
            const unsigned int * const sameR,
            const tuple *        const outRow) {
    int col;

    for (col = (int)xbegin; col < outPamP->width; ++col) {
        bool const duplicate = (sameL[col] != col && sameL[col] >= xbegin);

        unsigned int plane;

        for (plane = 0; plane < outPamP->depth; ++plane)
            outRow[col][plane] = duplicate ? outPamP->maxval : 0;
    }

    for (col = (int)xbegin - 1; col >= 0; --col) {
        bool const duplicate = (sameR[col] != col);

        unsigned int plane;

        for (plane = 0; plane < outPamP->depth; ++plane)
            outRow[col][plane] = duplicate ? outPamP->maxval : 0;
    }
}



static void
computeFixedPoint(const unsigned int * const same,
                  unsigned int *       const sameFp,
                  unsigned int         const width) {
/*----------------------------------------------------------------------------
  Compute the fixed point of same[] (i.e., sameFp[x] is
  same[same[same[...[same[x]]...]]]).
-----------------------------------------------------------------------------*/
    int col;

    for (col = width-1; col >= 0; --col) {
        if (same[col] != col)
            sameFp[col] = sameFp[same[col]];
        else {
            if (col < width-1)
                sameFp[col] = sameFp[col + 1] - 1;
            else
                sameFp[col] = col;
        }
    }
}



static void
averageFromPattern(struct pam *         const pamP,
                   tuple                const bgColor,
                   const tuple *        const textureRow,
                   const unsigned int * const same,
                   unsigned int *       const sameFp,
                   const tuple *        const outRow,
                   unsigned int *       const tuplesInCol) {
/*----------------------------------------------------------------------------
  Average the color of each non-background pattern tuple to every column that
  should have the same color.
-----------------------------------------------------------------------------*/
    int col;

    /* Initialize the tuple sums to zero. */

    for (col = 0; col < pamP->width; ++col) {
        unsigned int plane;
        for (plane = 0; plane < pamP->depth; ++plane)
            outRow[col][plane] = 0;
        tuplesInCol[col] = 0;
    }

    /* Accumulate the color of each non-background pattern tuple to
       every column that should have the same color.
    */
    for (col = pamP->width-1; col >= 0; --col) {
        tuple const onetuple = textureRow[(col+same[col])/2];
        unsigned int const targetcol = sameFp[col];
        int eqcol;

        if (!pnm_tupleequal(pamP, onetuple, bgColor)) {
            for (eqcol = pamP->width-1; eqcol >= 0; --eqcol) {
                if (sameFp[eqcol] == targetcol) {
                    unsigned int plane;
                    for (plane = 0; plane < pamP->depth; ++plane)
                        outRow[eqcol][plane] += onetuple[plane];
                    tuplesInCol[eqcol]++;
                }
            }
        }
    }
    /* Take the average of all colors associated with each column.
       Tuples that can be any color are assigned the same color as was
       previously assigned to their fixed-point column.
    */
    for (col = 0; col < pamP->width; ++col) {
        if (tuplesInCol[col] > 0) {
            unsigned int plane;
            for (plane = 0; plane < pamP->depth; ++plane)
                outRow[col][plane] /= tuplesInCol[col];
        } else
            pnm_assigntuple(pamP, outRow[col], bgColor);
    }
}



static void
smoothOutSpeckles(struct pam *   const pamP,
                  tuple          const bgColor,
                  unsigned int   const smoothing,
                  unsigned int * const tuplesInCol,
                  tuple *        const rowBuffer,
                  const tuple *  const outRow) {
/*----------------------------------------------------------------------------
  Smooth out small speckles of the background color lying between other
  colors.
-----------------------------------------------------------------------------*/
    unsigned int i;

    for (i = 0; i < smoothing; ++i) {
        int col;
        tuple * const scratchrow = rowBuffer;
        for (col = pamP->width-2; col >= 1; --col) {
            if (tuplesInCol[col] == 0) {
                /* Replace a background tuple with the average of its
                   left and right neighbors.
                */
                unsigned int plane;
                for (plane = 0; plane < pamP->depth; ++plane)
                    scratchrow[col][plane] = 0;
                if (!pnm_tupleequal(pamP, outRow[col-1], bgColor)) {
                    for (plane = 0; plane < pamP->depth; ++plane)
                        scratchrow[col][plane] += outRow[col-1][plane];
                    ++tuplesInCol[col];
                }
                if (!pnm_tupleequal(pamP, outRow[col+1], bgColor)) {
                    for (plane = 0; plane < pamP->depth; ++plane)
                        scratchrow[col][plane] += outRow[col+1][plane];
                    ++tuplesInCol[col];
                }
                if (tuplesInCol[col] > 0)
                    for (plane = 0; plane < pamP->depth; ++plane)
                        scratchrow[col][plane] /= tuplesInCol[col];
                else
                    pnm_assigntuple(pamP, scratchrow[col], outRow[col]);
            } else
                pnm_assigntuple(pamP, scratchrow[col], outRow[col]);
        }
        for (col = 1; col < pamP->width-1; ++col)
            pnm_assigntuple(pamP, outRow[col], scratchrow[col]);
    }
}



static void
replaceRemainingBackgroundWithPattern(outGenerator *       const outGenP,
                                      const unsigned int * const same,
                                      unsigned int         const row,
                                      const tuple *        const outRow) {

    const struct pam * const pamP = &outGenP->pam;
    tuple const bgColor = outGenP->textureP->bgColor;

    if (outGenP->textureP->replaceBgColor) {
        int col;
        for (col = outGenP->pam.width-1; col >= 0; --col) {
            if (pnm_tupleequal(pamP, outRow[col], bgColor)) {
                bool const duplicate = (same[col] != col);

                tuple newtuple;

                if (duplicate) {
                    assert(same[col] > col);
                    assert(same[col] < outGenP->pam.width);

                    newtuple = outRow[same[col]];
                } else
                    newtuple = outGenP->getTuple(outGenP, col, row);

                pnm_assigntuple(pamP, outRow[col], newtuple);
            }
        }
    }
}



static void
makeImageRowMts(outGenerator *       const outGenP,
                unsigned int         const row,
                const unsigned int * const same,
                unsigned int *       const colNumBuffer,
                tuple *              const rowBuffer,
                const tuple *        const outRow) {
/*----------------------------------------------------------------------------
  Make a row of a mapped-texture stereogram.
-----------------------------------------------------------------------------*/
    unsigned int * const sameFp = colNumBuffer;
        /* Fixed point of same[] */

    unsigned int * tuplesInCol;
        /* tuplesInCol[C] is the number of tuples averaged together to make
           Column C.
        */
    MALLOCARRAY(tuplesInCol, outGenP->pam.width);
    if (tuplesInCol == NULL)
        pm_error("Unable to allocate space for \"tuplesInCol\" array.");

    assert(outGenP->textureP);
    /* This is an original algorithm by Scott Pakin. */

    /*
      Compute the fixed point of same[] (i.e., sameFp[x] is
      same[same[same[...[same[x]]...]]]).
    */
    computeFixedPoint(same, sameFp, outGenP->pam.width);

    /* Average the color of each non-background pattern tuple to
       every column that should have the same color.
    */

    averageFromPattern(&outGenP->pam, outGenP->textureP->bgColor,
                       outGenP->textureP->imageData[row],
                       same, sameFp,
                       outRow, tuplesInCol);

    /* Smooth out small speckles of the background color lying between
       other colors.
    */
    smoothOutSpeckles(&outGenP->pam, outGenP->textureP->bgColor,
                      outGenP->textureP->smoothing,
                      tuplesInCol, rowBuffer, outRow);

    /* Replace any remaining background tuples with a pattern tuple. */

    replaceRemainingBackgroundWithPattern(outGenP, same, row, outRow);

    free(tuplesInCol);
}



static void
makeImageRow(outGenerator *       const outGenP,
             unsigned int         const row,
             unsigned int         const xbegin,
             unsigned int         const farWidth,
             int                  const yfillshift,
             const unsigned int * const sameL,
             const unsigned int * const sameR,
             const tuple *        const outRow) {
/*----------------------------------------------------------------------------
  sameR[N] is one of two things:

  sameR[N] == N means to generate a value for Column N independent of
  other columns in the row.

  sameR[N] > N means Column N should be identical to Column sameR[N].

  sameR[N] < N is not allowed.

  sameL[N] is one of two things:

  sameL[N] == N means to generate a value for Column N independent of
  other columns in the row.

  sameL[N] < N means Column N should be identical to Column sameL[N].

  sameL[N] > N is not allowed.
-----------------------------------------------------------------------------*/
    unsigned int const width  = outGenP->pam.width;
    unsigned int const height = outGenP->pam.height;

    unsigned int col;
    bool colHasBeenLinked;
    unsigned int lastLinkedCol;
        /* Last column to have been linked; meaningless if 'colHasBeenLinked'
           is false.
        */

    for (col = xbegin, colHasBeenLinked = false; col < width; ++col) {

        tuple newtuple;

        if (sameL[col] == col || sameL[col] < xbegin) {
            if (colHasBeenLinked && lastLinkedCol == col - 1)
                newtuple = outRow[lastLinkedCol];
            else {
                if (col < xbegin + farWidth)
                    newtuple = outGenP->getTuple(outGenP, col, row);
                else
                    newtuple = outGenP->getTuple(
                        outGenP, col, (row + height - yfillshift) % height);
            }
        } else {
            newtuple = outRow[sameL[col]];
            colHasBeenLinked = true;
            lastLinkedCol = col;
                /* Keep track of the last pixel to be constrained. */
        }
        pnm_assigntuple(&outGenP->pam, outRow[col], newtuple);
    }

    for (col = xbegin, colHasBeenLinked = false; col > 0; --col) {
        tuple newtuple;

        if (sameR[col-1] == col-1) {
            if (colHasBeenLinked && lastLinkedCol == col)
                newtuple = outRow[lastLinkedCol];
            else {
                if (col > xbegin - farWidth)
                    newtuple = outGenP->getTuple(outGenP, col-1, row);
                else
                    newtuple = outGenP->getTuple(
                        outGenP, col-1, (row + height - yfillshift) % height);
            }
        } else {
            newtuple = outRow[sameR[col-1]];
            colHasBeenLinked = true;
            lastLinkedCol = col - 1;
                /* Keep track of the last pixel to be constrained. */
        }
        pnm_assigntuple(&outGenP->pam, outRow[col-1], newtuple);
    }
}



static void
invertHeightRow(const struct pam * const heightPamP,
                tuple *            const tupleRow) {

    int col;

    for (col = 0; col < heightPamP->width; ++col)
        tupleRow[col][0] = heightPamP->maxval - tupleRow[col][0];
}



static void
makeOneImageRow(unsigned int         const row,
                outGenerator *       const outputGeneratorP,
                bool                 const makeMask,
                const unsigned int * const sameL,
                const unsigned int * const sameR,
                unsigned int *       const colNumBuffer,
                unsigned int         const xbegin,
                unsigned int         const farWidth,
                int                  const yfillshift,
                tuple *              const rowBuffer,
                tuple *              const outRow) {

    if (makeMask)
        makeMaskRow(&outputGeneratorP->pam, xbegin, sameL, sameR, outRow);
    else {
        if (outputGeneratorP->textureP)
            makeImageRowMts(outputGeneratorP, row, sameR, colNumBuffer,
                            rowBuffer, outRow);
        else
            makeImageRow(outputGeneratorP, row,
                         xbegin, farWidth, yfillshift, sameL, sameR, outRow);
    }
}



static void
constructRowTileable(const struct pam *   const inPamP,
                     outGenerator *       const outputGeneratorP,
                     bool                 const makeMask,
                     const unsigned int * const sameL,
                     const unsigned int * const sameR,
                     unsigned int         const farWidth,
                     int                  const yfillshift,
                     unsigned int         const row,
                     tuple *              const outRow,
                     tuple *              const outRowBuf1,
                     tuple *              const outRowBuf2,
                     unsigned int *       const colNumBuf2) {

    tuple * const outRowMax = outRowBuf1;

    unsigned int col;

    /* Create two rows with extreme xbegin values and blend the second
       into the first.  outRow[] serves as both the buffer for the xbegin=0
       version and the merged output.  outRowMax[] is the buffer for the
       xbegin=maximum case.
    */
    makeOneImageRow(row, outputGeneratorP, makeMask, sameL, sameR, colNumBuf2,
                    farWidth, yfillshift, 0, outRowBuf2, outRow);

    makeOneImageRow(row, outputGeneratorP, makeMask, sameL, sameR, colNumBuf2,
                    farWidth, yfillshift, inPamP->width - 1, outRowBuf2, outRowMax);

    for (col = 0; col < inPamP->width; ++col) {
        unsigned int plane;
        unsigned int oplane;

        if (outputGeneratorP->pam.have_opacity)
            oplane = outputGeneratorP->pam.opacity_plane;

        for (plane = 0; plane < outputGeneratorP->pam.color_depth; ++plane) {

            sample samp, sampMax;

            if (outputGeneratorP->pam.have_opacity) {
                /* If one sample is fully transparent, use the
                   other sample for both purposes
                */
                if (outRow[col][oplane] == 0)
                    samp = sampMax = outRowMax[col][plane];
                else if (outRowMax[col][oplane] == 0)
                    samp = sampMax = outRow[col][plane];
                else {
                    samp    = outRow[col][plane];
                    sampMax = outRowMax[col][plane];
                }
            } else {
                samp    = outRow[col][plane];
                sampMax = outRowMax[col][plane];
            }

            outRow[col][plane] =
                (col*sampMax + (inPamP->width - col - 1)*samp) /
                (inPamP->width - 1);
        }
        if (outputGeneratorP->pam.have_opacity) {
            sample samp, sampMax;

            /* Take the maximum alpha for partially transparent samples. */
            samp    = outRow[col][oplane];
            sampMax = outRowMax[col][oplane];
            outRow[col][oplane] = MAX(samp, sampMax);
        }
    }
}



static void
doRow(const struct pam * const inPamP,
      outGenerator *     const outputGeneratorP,
      double             const depthOfField,
      double             const eyesep,
      unsigned int       const dpi,
      bool               const crossEyed,
      bool               const makeMask,
      bool               const tileable,
      unsigned int       const magnifypat,
      unsigned int       const smoothing,
      unsigned int       const xbegin,
      unsigned int       const farWidth,
      int                const yfillshift,
      unsigned int       const row,
      tuple *            const inRow,
      tuple *            const outRowBuf0,
      tuple *            const outRowBuf1,
      tuple *            const outRowBuf2,
      unsigned int *     const colNumBuf0,
      unsigned int *     const colNumBuf1,
      unsigned int *     const colNumBuf2) {

    tuple *        const outRow = outRowBuf0;
    unsigned int * const sameL  = colNumBuf0;
        /* sameL[N] is the column number of a pixel to the
           left forced to have the same color as the one in column N
        */
    unsigned int * const sameR = colNumBuf1;
        /* sameR[N] is the column number of a pixel to the
           right forced to have the same color as the one in column N
        */

    pnm_readpamrow(inPamP, inRow);

    if (crossEyed)
        /* Invert heights for cross-eyed (as opposed to wall-eyed)
           people.
        */
        invertHeightRow(inPamP, inRow);

    /* Determine color constraints. */
    makeStereoRow(inPamP, inRow, sameL, sameR, depthOfField, eyesep, dpi,
                  ROUNDU(eyesep * dpi)/(magnifypat * 2),
                  smoothing);

    /* Construct a single row. */
    if (tileable) {
        constructRowTileable(inPamP, outputGeneratorP, makeMask,
                             sameL, sameR,
                             farWidth, yfillshift,
                             row, outRow,
                             outRowBuf1, outRowBuf2, colNumBuf2);

    } else {
        makeOneImageRow(row, outputGeneratorP, makeMask,
                        sameL, sameR, colNumBuf2,
                        xbegin, farWidth, yfillshift,
                        outRowBuf1, outRow);
    }

    /* Write the resulting row. */
    pnm_writepamrow(&outputGeneratorP->pam, outRow);
}



static void
makeImageRows(const struct pam * const inPamP,
              outGenerator *     const outputGeneratorP,
              double             const depthOfField,
              double             const eyesep,
              unsigned int       const dpi,
              bool               const crossEyed,
              bool               const makeMask,
              bool               const tileable,
              unsigned int       const magnifypat,
              unsigned int       const smoothing,
              unsigned int       const xbegin,
              int                const yfillshift) {

    tuple * inRow;    /* Buffer for use in reading from the height-map image */
    tuple * outRowBuf0; /* Buffer for use in generating output rows */
    tuple * outRowBuf1; /* Buffer for use in generating output rows */
    tuple * outRowBuf2; /* Buffer for use in generating output rows */
    unsigned int * colNumBuf0;
    unsigned int * colNumBuf1;
    unsigned int * colNumBuf2;
    unsigned int row;      /* Current row in the input and output files */
    unsigned int pixelEyesep;
    unsigned int farWidth;

    inRow = pnm_allocpamrow(inPamP);
    outRowBuf0 = pnm_allocpamrow(&outputGeneratorP->pam);
    outRowBuf1 = pnm_allocpamrow(&outputGeneratorP->pam);
    outRowBuf2 = pnm_allocpamrow(&outputGeneratorP->pam);
    MALLOCARRAY(colNumBuf0, inPamP->width);
    if (colNumBuf0 == NULL)
        pm_error("Unable to allocate space for %u column buffer",
                 inPamP->width);
    MALLOCARRAY(colNumBuf1, inPamP->width);
    if (colNumBuf1 == NULL)
        pm_error("Unable to allocate space for %u column buffer",
                 inPamP->width);
    MALLOCARRAY(colNumBuf2, inPamP->width);
    if (colNumBuf2 == NULL)
        pm_error("Unable to allocate space for %u column buffer",
                 inPamP->width);

    pixelEyesep = ROUNDU(eyesep * dpi);
    farWidth = pixelEyesep/(magnifypat * 2);

    for (row = 0; row < inPamP->height; ++row) {
        doRow(inPamP, outputGeneratorP,  depthOfField, eyesep, dpi,
              crossEyed, makeMask, tileable, magnifypat, smoothing, xbegin,
              farWidth, yfillshift, row,
              inRow, outRowBuf0, outRowBuf1, outRowBuf2,
              colNumBuf0, colNumBuf1, colNumBuf2);
    }

    free(colNumBuf2);
    free(colNumBuf1);
    free(colNumBuf0);
    pnm_freepamrow(outRowBuf1);
    pnm_freepamrow(outRowBuf0);
    pnm_freepamrow(inRow);
}



static void
produceStereogram(FILE *             const ifP,
                  struct cmdlineInfo const cmdline) {

    struct pam inPam;    /* PAM information for the height-map file */
    outGenerator * outputGeneratorP;
        /* Handle of an object that generates background pixels */
    unsigned int xbegin;
        /* x coordinate separating left-to-right from right-to-left coloring */

    pnm_readpaminit(ifP, &inPam, PAM_STRUCT_SIZE(tuple_type));

    createoutputGenerator(cmdline, &inPam, &outputGeneratorP);

    if (cmdline.verbose) {
        reportImageParameters("Input (height map) file", &inPam);
        if (inPam.depth > 1)
            pm_message("Ignoring all but the first plane of input.");
        reportImageParameters("Output (stereogram) file",
                              &outputGeneratorP->pam);
    }

    pnm_writepaminit(&outputGeneratorP->pam);

    if (cmdline.xbeginSpec == 0)
        xbegin = outputGeneratorP->pam.width/2;
    else {
        xbegin = cmdline.xbegin;
        if (xbegin >= outputGeneratorP->pam.width)
            pm_error("-xbegin must be less than the image width (%d)",
                     outputGeneratorP->pam.width);
    }

    if (cmdline.guidetop)
        drawguides(cmdline.guidesize, &outputGeneratorP->pam,
                   cmdline.eyesep,
                   cmdline.dpi, cmdline.depth);

    makeImageRows(&inPam, outputGeneratorP,
                  cmdline.depth, cmdline.eyesep, cmdline.dpi,
                  cmdline.crosseyed, cmdline.makemask, cmdline.tileable,
                  cmdline.magnifypat, cmdline.smoothing, xbegin,
                  cmdline.yfillshift);

    if (cmdline.guidebottom)
        drawguides(cmdline.guidesize, &outputGeneratorP->pam,
                   cmdline.eyesep, cmdline.dpi, cmdline.depth);

    if (cmdline.texfile) {
        pnm_freepamarray(outputGeneratorP->textureP->imageData,
                         &outputGeneratorP->textureP->pam);
        free(outputGeneratorP->textureP);
    }
    destroyoutputGenerator(outputGeneratorP);
}



static void
reportParameters(struct cmdlineInfo const cmdline) {

    unsigned int const pixelEyesep =
        ROUNDU(cmdline.eyesep * cmdline.dpi);
    unsigned int const sep0 =
        separation(0, cmdline.eyesep, cmdline.dpi, cmdline.depth);
    unsigned int const sep1 =
        separation(1, cmdline.eyesep, cmdline.dpi, cmdline.depth);

    pm_message("Eye separation: %.4g inch * %d DPI = %u pixels",
               cmdline.eyesep, cmdline.dpi, pixelEyesep);

    if (cmdline.magnifypat > 1)
        pm_message("Background magnification: %uX * %uX",
                   cmdline.magnifypat, cmdline.magnifypat);
    pm_message("\"Optimal\" (far) pattern width: %u / (%u * 2) = %u pixels",
               pixelEyesep, cmdline.magnifypat,
               pixelEyesep/(cmdline.magnifypat * 2));
    pm_message("Near pattern width: %u / %u = %u pixels",
               sep1, cmdline.magnifypat, sep1 / cmdline.magnifypat);
    pm_message("Unique 3-D depth levels possible: %u", sep0 - sep1 + 1);
    if (cmdline.patfile && (cmdline.xshift || cmdline.yshift))
        pm_message("Pattern shift: (%d, %d)", cmdline.xshift, cmdline.yshift);
}



int
main(int argc, const char *argv[]) {

    struct cmdlineInfo cmdline;      /* Parsed command line */
    FILE * ifP;

    pm_proginit(&argc, argv);

    parseCommandLine(argc, argv, &cmdline);

    if (cmdline.verbose)
        reportParameters(cmdline);

    ifP = pm_openr(cmdline.inputFilespec);

    /* Produce a stereogram. */
    produceStereogram(ifP, cmdline);

    pm_close(ifP);

    return 0;
}