~cspiel/enblend/staging

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
/*
 * Copyright (C) 2004-2007 Andrew Mihal
 *
 * This file is part of Enblend.
 *
 * Enblend is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Enblend is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Enblend; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
#ifndef __ENFUSE_H__
#define __ENFUSE_H__

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

#include <iostream>
#include <iomanip>
#include <list>
#include <stdio.h>

#include <boost/static_assert.hpp>

#include "common.h"
#include "openmp.h"
#include "numerictraits.h"
#include "fixmath.h"
#include "assemble.h"
#include "blend.h"
#include "bounds.h"
#include "pyramid.h"
#include "mga.h"

#include "vigra/flatmorphology.hxx"
#include "vigra/functorexpression.hxx"
#include "vigra/impex.hxx"
#include "vigra/initimage.hxx"
#include "vigra/inspectimage.hxx"
#include "vigra/stdimage.hxx"
#include "vigra/transformimage.hxx"

#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/construct.hpp>

using std::cout;
using std::endl;
using std::list;
using std::pair;

using vigra::functor::Arg1;
using vigra::functor::Arg2;
using vigra::functor::Param;
using vigra::BasicImage;
using vigra::CachedFileImage;
using vigra::CachedFileImageDirector;
using vigra::FImage;
using vigra::FindMinMax;
using vigra::ImageExportInfo;
using vigra::ImageImportInfo;
using vigra::initImage;
using vigra::initImageIf;
using vigra::inspectImage;
using vigra::NumericTraits;
using vigra::Size2D;
using vigra::VigraFalseType;
using vigra::VigraTrueType;
using vigra::Kernel1D;
using vigra::VectorNormFunctor;

using boost::lambda::_1;
using boost::lambda::_2;
using boost::lambda::bind;
using boost::lambda::const_parameters;

namespace enblend {

static inline double square(double x)
{
    return x * x;
}


static inline double gaussDistribution(double x, double mu, double sigma)
{
    return exp(-0.5 * square((x - mu) / sigma));
}


// Keep sum and sum-of-squares together for improved CPU-cache locality.
template <typename T>
struct ScratchPad {
    ScratchPad() : sum(T()), sumSqr(T()), n(size_t()) {}

    T sum;
    T sumSqr;
    size_t n;
};


template <class SrcIterator, class SrcAccessor,
          class MaskIterator, class MaskAccessor,
          class DestIterator, class DestAccessor>
void localStdDevIf(SrcIterator src_ul, SrcIterator src_lr, SrcAccessor src_acc,
                   MaskIterator mask_ul, MaskAccessor mask_acc,
                   DestIterator dest_ul, DestAccessor dest_acc,
                   Size2D size)
{
    typedef typename NumericTraits<typename SrcAccessor::value_type>::RealPromote SrcSumType;
    typedef NumericTraits<typename DestAccessor::value_type> DestTraits;
    typedef typename SrcIterator::PixelType SrcPixelType;
    typedef typename SrcIterator::row_iterator SrcRowIterator;
    typedef typename MaskIterator::row_iterator MaskRowIterator;
    typedef typename DestIterator::PixelType DestPixelType;
    typedef ScratchPad<SrcSumType> ScratchPadType;
    typedef std::vector<ScratchPadType> ScratchPadArray;
    typedef typename ScratchPadArray::iterator ScratchPadArrayIterator;

    vigra_precondition(size.x > 1 && size.y > 1,
                       "localStdDevIf(): window for local variance must be at least 2x2");
    vigra_precondition(src_lr.x - src_ul.x >= size.x &&
                       src_lr.y - src_ul.y >= size.y,
                       "localStdDevIf(): window larger than image");

    const typename SrcIterator::difference_type imageSize = src_lr - src_ul;
    ScratchPadArray scratchPad(imageSize.x + 1);

    const Diff2D border(size.x / 2, size.y / 2);
    const Diff2D nextUpperRight(size.x / 2 + 1, -size.y / 2);

    SrcIterator const srcEnd(src_lr - border);
    SrcIterator const srcEndXm1(srcEnd - Diff2D(1, 0));

    // For each row in the source image...
#ifdef OPENMP
#pragma omp parallel for firstprivate (scratchPad)
#endif
    for (int row = 0; row < imageSize.y - 2 * border.y; ++row)
    {
        SrcIterator srcRow(src_ul + border + Diff2D(0, row));
        MaskIterator maskRow(mask_ul + border + Diff2D(0, row));
        DestIterator destRow(dest_ul + border + Diff2D(0, row));

        // Row's running values
        SrcSumType sum = NumericTraits<SrcSumType>::zero();
        SrcSumType sumSqr = NumericTraits<SrcSumType>::zero();
        size_t n = 0;

        SrcIterator const windowSrcUpperLeft(srcRow - border);
        SrcIterator const windowSrcLowerRight(srcRow + border);
        SrcIterator windowSrc;
        MaskIterator const windowMaskUpperLeft(maskRow - border);
        MaskIterator windowMask;
        ScratchPadArrayIterator spCol;

        // Initialize running-sums of this row
        for (windowSrc = windowSrcUpperLeft, windowMask = windowMaskUpperLeft,
                 spCol = scratchPad.begin();
             windowSrc.x <= windowSrcLowerRight.x;
             ++windowSrc.x, ++windowMask.x, ++spCol)
        {
            SrcSumType sumInit = NumericTraits<SrcSumType>::zero();
            SrcSumType sumSqrInit = NumericTraits<SrcSumType>::zero();
            size_t nInit = 0;

            for (windowSrc.y = windowSrcUpperLeft.y, windowMask.y = windowMaskUpperLeft.y;
                 windowSrc.y <= windowSrcLowerRight.y;
                 ++windowSrc.y, ++windowMask.y)
            {
                if (mask_acc(windowMask))
                {
                    const SrcSumType value = src_acc(windowSrc);
                    sumInit += value;
                    sumSqrInit += square(value);
                    ++nInit;
                }
            }

            // Set scratch pad's column-wise values
            spCol->sum = sumInit;
            spCol->sumSqr = sumSqrInit;
            spCol->n = nInit;

            // Update totals
            sum += sumInit;
            sumSqr += sumSqrInit;
            n += nInit;
        }

        // Write one row of results
        SrcIterator srcCol(srcRow);
        MaskIterator maskCol(maskRow);
        DestIterator destCol(destRow);
        ScratchPadArrayIterator old(scratchPad.begin());
        ScratchPadArrayIterator next(scratchPad.begin() + size.x);

        while (true)
        {
            // Compute standard deviation
            if (mask_acc(maskCol))
            {
                const SrcSumType result =
                    n <= 1 ?
                    NumericTraits<SrcSumType>::zero() :
                    sqrt((sumSqr - square(sum) / n) / (n - 1));
                dest_acc.set(DestTraits::fromRealPromote(result), destCol);
            }
            if (srcCol.x == srcEndXm1.x)
            {
                break;
            }

            // Compute auxilliary values of next column
            SrcSumType sumInit = NumericTraits<SrcSumType>::zero();
            SrcSumType sumSqrInit = NumericTraits<SrcSumType>::zero();
            size_t nInit = 0;

            for (windowSrc = srcCol + nextUpperRight, windowMask = maskCol + nextUpperRight;
                 windowSrc.y <= windowSrcLowerRight.y;
                 ++windowSrc.y, ++windowMask.y)
            {
                if (mask_acc(windowMask))
                {
                    const SrcSumType value = src_acc(windowSrc);
                    sumInit += value;
                    sumSqrInit += square(value);
                    ++nInit;
                }
            }

            // Set sums of next column
            next->sum = sumInit;
            next->sumSqr = sumSqrInit;
            next->n = nInit;

            // Update totals
            sum += sumInit - old->sum;
            sumSqr += sumSqrInit - old->sumSqr;
            n += nInit - old->n;

            // Advance to next column
            ++srcCol.x;
            ++maskCol.x;
            ++destCol.x;
            ++old;
            ++next;
        }
    }
}


template <typename InputPixelType, typename ResultPixelType>
class Histogram
{
    enum {GRAY = 0, CHANNELS = 3};

public:
    typedef NumericTraits<InputPixelType> InputPixelTraits;
    typedef typename InputPixelTraits::ValueType KeyType; // scalar values are our keys
    typedef typename InputPixelTraits::isScalar pixelIsScalar;
    typedef unsigned DataType;  // pixel counts are our data
    typedef NumericTraits<ResultPixelType> ResultPixelTraits;
    typedef typename ResultPixelTraits::ValueType ResultType;
    typedef map<KeyType, DataType> MapType;
    typedef pair<KeyType, DataType> PairType;
    typedef typename MapType::const_iterator MapConstIterator;
    typedef typename MapType::iterator MapIterator;
    typedef typename MapType::size_type MapSizeType;

    Histogram() {clear();}

    void clear() {
        for (int channel = 0; channel < CHANNELS; ++channel) {
            totalCount[channel] = DataType();
            histogram[channel].clear();
        }
    }

    static void setPrecomputedEntropySize(size_t size) {
        // PERFORMANCE: setPrecomputedEntropySize is a pure
        // performance enhancer otherwise the function is completely
        // redundant.  It derives its existence from the facts that
        // computing the entropy "p * log(p)" given the probability
        // "p" is an expensive operation _and_ most of the time the
        // moving window is filled completely, i.e., no pixel is
        // masked.
        precomputedSize = size;
        delete [] precomputedLog;
        delete [] precomputedEntropy;
        if (size == 0)
        {
            precomputedLog = NULL;
            precomputedEntropy = NULL;
        }
        else
        {
            precomputedLog = new double[size + 1];
            vigra_precondition(precomputedLog != NULL,
                               "Histogram::setPrecomputedSize: failed to allocate log-preevaluate memory");
            precomputedEntropy = new double[size + 1];
            vigra_precondition(precomputedEntropy != NULL,
                               "Histogram::setPrecomputedSize: failed to allocate entropy-preevaluate memory");
            precomputedLog[0] = 0.0; // just to have a reliable value
            precomputedEntropy[0] = 0.0;
            for (size_t i = 1; i <= size; ++i)
            {
                const double p = static_cast<double>(i) / static_cast<double>(size);
                precomputedLog[i] = static_cast<double>(i);
                precomputedEntropy[i] = p * log(p);
            }
        }
    }

    Histogram& operator=(const Histogram& other) {
        if (this != &other)
        {
            for (int channel = 0; channel < CHANNELS; ++channel)
            {
                totalCount[channel] = other.totalCount[channel];
                histogram[channel] = other.histogram[channel];
            }
        }
        return *this;
    }

    void insert(const InputPixelType& x) {insertFun(x, pixelIsScalar());}
    void insert(const Histogram* other) {insertFun(other, pixelIsScalar());}

    void erase(const InputPixelType& x) {eraseFun(x, pixelIsScalar());}
    void erase(const Histogram* other) {eraseFun(other, pixelIsScalar());}

    ResultPixelType entropy() const {return entropyFun(pixelIsScalar());}

protected:
    void insertInChannel(int channel, const PairType& keyval) {
        // PERFORMANCE: The actual insertion code below code is a much
        // faster version of
        //     MapIterator const i = histogram[channel].find(keyval.first);
        //     if (i == histogram[channel].end())
        //         histogram[channel].insert(keyval);
        //     else i->second += keyval.second;
        MapIterator const lowerBound = histogram[channel].lower_bound(keyval.first);
        const DataType count = keyval.second;
        if (lowerBound != histogram[channel].end() &&
            !(histogram[channel].key_comp()(keyval.first, lowerBound->first)))
        {
            lowerBound->second += count;
        }
        else
        {
            histogram[channel].insert(lowerBound, keyval);
        }
        totalCount[channel] += count;
    }

    void eraseInChannel(int channel, const PairType& keyval) {
        MapIterator const i = histogram[channel].find(keyval.first);
        assert(i != histogram[channel].end());
        DataType& c = i->second;
        const DataType count = keyval.second;
        if (c > count)
        {
            c -= count;
        }
        else
        {
            // PERFORMANCE: It is _much_ faster to erase unneeded bins
            // right away than it is e.g. to periodically (think of
            // every column) cleaning up the whole map while wasting
            // time in lots of comparisons until then.
            histogram[channel].erase(i);
        }
        totalCount[channel] -= count;
    }

    double entropyOfChannel(int channel) const {
        const DataType total = totalCount[channel];
        const MapSizeType actualBins = histogram[channel].size();
        if (total == 0 || actualBins <= 1)
        {
            return 0.0;
        }
        else
        {
            double e = 0.0;
            MapConstIterator const end = histogram[channel].end();
            if (total == precomputedSize)
            {
                for (MapConstIterator i = histogram[channel].begin(); i != end; ++i)
                {
                    e += precomputedEntropy[i->second];
                }
                return -e / precomputedLog[actualBins];
            }
            else
            {
                for (MapConstIterator i = histogram[channel].begin(); i != end; ++i)
                {
                    const double p = i->second / static_cast<double>(total);
                    e += p * log(p);
                }
                return -e / log(static_cast<double>(actualBins));
            }
        }
    }

    // Grayscale
    void insertFun(const InputPixelType& x, VigraTrueType) {
        insertInChannel(GRAY, PairType(x, 1U));
    }

    void insertFun(const Histogram* other, VigraTrueType) {
        MapConstIterator const end = other->histogram[GRAY].end();
        for (MapConstIterator i = other->histogram[GRAY].begin(); i != end; ++i)
        {
            insertInChannel(GRAY, *i);
        }
    }

    void eraseFun(const InputPixelType& x, VigraTrueType) {
        eraseInChannel(GRAY, PairType(x, 1U));
    }

    void eraseFun(const Histogram* other, VigraTrueType) {
        MapConstIterator const end = other->histogram[GRAY].end();
        for (MapConstIterator i = other->histogram[GRAY].begin(); i != end; ++i)
        {
            eraseInChannel(GRAY, *i);
        }
    }

    ResultPixelType entropyFun(VigraTrueType) const {
        const double max = static_cast<double>(NumericTraits<KeyType>::max());
        return ResultPixelType(ResultPixelTraits::fromRealPromote(entropyOfChannel(GRAY) * max));
    }

    // RGB
    void insertFun(const InputPixelType& x, VigraFalseType) {
        for (int channel = 0; channel < CHANNELS; ++channel) {
            insertInChannel(channel, PairType(x[channel], 1U));
        }
    }

    void insertFun(const Histogram* other, VigraFalseType) {
        for (int channel = 0; channel < CHANNELS; ++channel)
        {
            MapConstIterator const end = other->histogram[channel].end();
            for (MapConstIterator i = other->histogram[channel].begin(); i != end; ++i)
            {
                insertInChannel(channel, *i);
            }
        }
    }

    void eraseFun(const InputPixelType& x, VigraFalseType) {
        for (int channel = 0; channel < CHANNELS; ++channel) {
            eraseInChannel(channel, PairType(x[channel], 1U));
        }
    }

    void eraseFun(const Histogram* other, VigraFalseType) {
        for (int channel = 0; channel < CHANNELS; ++channel)
        {
            MapConstIterator const end = other->histogram[channel].end();
            for (MapConstIterator i = other->histogram[channel].begin(); i != end; ++i)
            {
                eraseInChannel(channel, *i);
            }
        }
    }

    ResultPixelType entropyFun(VigraFalseType) const {
        const double max = static_cast<double>(NumericTraits<KeyType>::max());
        return ResultPixelType(NumericTraits<ResultType>::fromRealPromote(entropyOfChannel(0) * max),
                               NumericTraits<ResultType>::fromRealPromote(entropyOfChannel(1) * max),
                               NumericTraits<ResultType>::fromRealPromote(entropyOfChannel(2) * max));
    }

private:
    static size_t precomputedSize;
    static double* precomputedLog;
    static double* precomputedEntropy;
    MapType histogram[CHANNELS];
    DataType totalCount[CHANNELS];
};


template <class SrcIterator, class SrcAccessor,
          class MaskIterator, class MaskAccessor,
          class DestIterator, class DestAccessor>
void localEntropyIf(SrcIterator src_ul, SrcIterator src_lr, SrcAccessor src_acc,
                    MaskIterator mask_ul, MaskAccessor mask_acc,
                    DestIterator dest_ul, DestAccessor dest_acc,
                    Size2D size)
{
    typedef NumericTraits<typename DestAccessor::value_type> DestTraits;
    typedef typename SrcIterator::PixelType SrcPixelType;
    typedef typename SrcIterator::row_iterator SrcRowIterator;
    typedef typename MaskIterator::row_iterator MaskRowIterator;
    typedef typename DestIterator::PixelType DestPixelType;
    typedef Histogram<SrcPixelType, DestPixelType> ScratchPadType;

    vigra_precondition(src_lr.x - src_ul.x >= size.x &&
                       src_lr.y - src_ul.y >= size.y,
                       "localEntropyIf(): window larger than image");

    const typename SrcIterator::difference_type imageSize = src_lr - src_ul;
    ScratchPadType* const scratchPad = new ScratchPadType[imageSize.y + 1];

    ScratchPadType::setPrecomputedEntropySize(size.x * size.y);

    const Diff2D border(size.x / 2, size.y / 2);
    const Diff2D deltaX(size.x / 2, 0);
    const Diff2D deltaXp1(size.x / 2 + 1, 0);
    const Diff2D deltaY(0, size.y / 2);

    // Fill scratch pad for the first time.
    {
        SrcIterator srcRow(src_ul + deltaX);
        SrcIterator const srcEnd(src_lr - deltaX);
        MaskIterator maskRow(mask_ul + deltaX);
        ScratchPadType* spRow(scratchPad);

        for (; srcRow.y < srcEnd.y; ++srcRow.y, ++maskRow.y, ++spRow)
        {
            SrcIterator srcCol(srcRow - deltaX);
            SrcIterator srcColEnd(srcRow + deltaX);
            MaskIterator maskCol(maskRow - deltaX);

            for (; srcCol.x <= srcColEnd.x; ++srcCol.x, ++maskCol.x)
            {
                if (mask_acc(maskCol))
                {
                    spRow->insert(src_acc(srcCol));
                }
            }
        }
    }

    // Iterate through the image
    {
        SrcIterator srcCol(src_ul + border);
        SrcIterator const srcEnd(src_lr - border);
        MaskIterator maskCol(mask_ul + border);
        DestIterator destCol(dest_ul + border);

        ScratchPadType hist;

        // For each column in the source image...
        for (; srcCol.x < srcEnd.x; ++srcCol.x, ++maskCol.x, ++destCol.x)
        {
            SrcIterator srcRow(srcCol);
            MaskIterator maskRow(maskCol);
            DestIterator destRow(destCol);
            ScratchPadType* spRow(scratchPad + border.y);

            // Initialize running histogram of this column
            hist.clear();
            for (ScratchPadType* s = spRow - border.y; s <= spRow + border.y; ++s)
            {
                hist.insert(s);
            }

            // Write one column of results
            for (; srcRow.y < srcEnd.y; ++srcRow.y, ++maskRow.y, ++destRow.y, ++spRow)
            {
                // Compute entropy
                if (mask_acc(maskRow))
                {
                    dest_acc.set(hist.entropy(), destRow);
                }

                // Update running histogram to next row
                hist.erase(spRow - border.y); // remove oldest row
                hist.insert(spRow + border.y + 1); // add next row
            }

            // Update scratch pad to next column
            for (srcRow = srcCol - deltaY, maskRow = maskCol - deltaY, spRow = scratchPad;
                 srcRow.y < src_lr.y;
                 ++srcRow.y, ++maskRow.y, ++spRow)
            {
                if (mask_acc(maskRow - deltaX))
                {
                    // remove oldest column
                    spRow->erase(src_acc(srcRow - deltaX));
                }
                if (mask_acc(maskRow + deltaXp1))
                {
                    // add next column
                    spRow->insert(src_acc(srcRow + deltaXp1));
                }
            }
        }
    }

    ScratchPadType::setPrecomputedEntropySize(0);
    delete [] scratchPad;
}


template <typename SrcIterator, typename SrcAccessor,
          typename MaskIterator, typename MaskAccessor,
          typename DestIterator, typename DestAccessor>
inline void
localEntropyIf(triple<SrcIterator, SrcIterator, SrcAccessor> src,
               pair<MaskIterator, MaskAccessor> mask,
               pair<DestIterator, DestAccessor> dest,
               Size2D size)
{
    localEntropyIf(src.first, src.second, src.third,
                   mask.first, mask.second,
                   dest.first, dest.second,
                   size);
}


template <typename SrcIterator, typename SrcAccessor,
          typename MaskIterator, typename MaskAccessor,
          typename DestIterator, typename DestAccessor>
inline void
localStdDevIf(triple<SrcIterator, SrcIterator, SrcAccessor> src,
              pair<MaskIterator, MaskAccessor> mask,
              pair<DestIterator, DestAccessor> dest,
              Size2D size)
{
    localStdDevIf(src.first, src.second, src.third,
                  mask.first, mask.second,
                  dest.first, dest.second,
                  size);
}


template <typename MaskPixelType>
class ImageMaskMultiplyFunctor {
public:
    ImageMaskMultiplyFunctor(MaskPixelType d) :
        divisor(NumericTraits<MaskPixelType>::toRealPromote(d)) {}

    template <typename ImagePixelType>
    ImagePixelType operator()(const ImagePixelType& iP, const MaskPixelType& maskP) const {
        typedef typename NumericTraits<ImagePixelType>::RealPromote RealImagePixelType;

        // Convert mask pixel to blend coefficient in range [0.0, 1.0].
        const double maskCoeff = NumericTraits<MaskPixelType>::toRealPromote(maskP) / divisor;
        const RealImagePixelType riP = NumericTraits<ImagePixelType>::toRealPromote(iP);
        const RealImagePixelType blendP = riP * maskCoeff;
        return NumericTraits<ImagePixelType>::fromRealPromote(blendP);
    }

protected:
    double divisor;
};


template <typename InputType, typename InputAccessor, typename ResultType>
class ExposureFunctor {
public:
    typedef ResultType result_type;

    ExposureFunctor(double w, double m, double s, InputAccessor a) :
        weight(w), mu(m), sigma(s), acc(a) {}

    inline ResultType operator()(const InputType& a) const {
        typedef typename NumericTraits<InputType>::isScalar srcIsScalar;
        return f(a, srcIsScalar());
    }

protected:
    // grayscale
    template <typename T>
    inline ResultType f(const T& a, VigraTrueType) const {
        typedef typename NumericTraits<T>::RealPromote RealType;
        const RealType ra = NumericTraits<T>::toRealPromote(a);
        const double b = NumericTraits<T>::max() * mu;
        const double c = NumericTraits<T>::max() * sigma;
        return NumericTraits<ResultType>::fromRealPromote(weight *
                                                          gaussDistribution(ra, b, c));
    }

    // RGB
    template <typename T>
    inline ResultType f(const T& a, VigraFalseType) const {
        return f(acc.operator()(a), VigraTrueType());
    }

    double weight;
    double mu;
    double sigma;
    InputAccessor acc;
};


template <typename InputType, typename ResultType>
class SaturationFunctor {
public:
    typedef ResultType result_type;

    SaturationFunctor(double w) : weight(w) {}

    inline ResultType operator()(const InputType& a) const {
        typedef typename NumericTraits<InputType>::isScalar srcIsScalar;
        return f(a, srcIsScalar());
    }

protected:
    // grayscale
    template <typename T>
    inline ResultType f(const T& a, VigraTrueType) const {
        return NumericTraits<ResultType>::zero();
    }

    // RGB
    template <typename T>
    inline ResultType f(const T& a, VigraFalseType) const {
        typedef typename T::value_type TComponentType;
        typedef typename NumericTraits<TComponentType>::RealPromote RTComponentType;
        const RTComponentType rsa = NumericTraits<TComponentType>::toRealPromote(a.saturation());
        return NumericTraits<ResultType>::fromRealPromote(weight * rsa / NumericTraits<TComponentType>::max());
    }

    double weight;
};


template <typename InputType, typename ScaleType, typename ResultType>
class ContrastFunctor {
public:
    typedef ResultType result_type;

    ContrastFunctor(double w) : weight(w) {}

    inline ResultType operator()(const InputType& a) const {
        typedef typename NumericTraits<InputType>::isScalar srcIsScalar;
        typedef typename NumericTraits<ScaleType>::isIntegral scaleIsIntegral;
        return f(a, srcIsScalar(), scaleIsIntegral());
    }

protected:
    // grayscale, integral
    template <typename T>
    inline ResultType f(const T& a, VigraTrueType, VigraTrueType) const {
        const typename NumericTraits<T>::RealPromote ra = NumericTraits<T>::toRealPromote(a);
        return NumericTraits<ResultType>::fromRealPromote(weight * ra / NumericTraits<ScaleType>::max());
    }

    // grayscale, floating-point
    template <typename T>
    inline ResultType f(const T& a, VigraTrueType, VigraFalseType) const {
        const typename NumericTraits<T>::RealPromote ra = NumericTraits<T>::toRealPromote(a);
        return NumericTraits<ResultType>::fromRealPromote(weight * ra);
    }

    // RGB, integral
    template <typename T>
    inline ResultType f(const T& a, VigraFalseType, VigraTrueType) const {
        typedef typename T::value_type TComponentType;
        typedef typename NumericTraits<TComponentType>::RealPromote RealTComponentType;
        typedef typename ScaleType::value_type ScaleComponentType;
        const RealTComponentType ra = static_cast<RealTComponentType>(a.lightness());
        return NumericTraits<ResultType>::fromRealPromote(weight * ra / NumericTraits<ScaleComponentType>::max());
    }

    // RGB, floating-point
    template <typename T>
    inline ResultType f(const T& a, VigraFalseType, VigraFalseType) const {
        typedef typename T::value_type TComponentType;
        typedef typename NumericTraits<TComponentType>::RealPromote RealTComponentType;
        const RealTComponentType ra = static_cast<RealTComponentType>(a.lightness());
        return NumericTraits<ResultType>::fromRealPromote(weight * ra);
    }

    double weight;
};


template <typename InputType, typename ResultType>
class EntropyFunctor {
public:
    typedef NumericTraits<InputType> InputTraits;
    typedef NumericTraits<ResultType> ResultTraits;
    typedef ResultType result_type;

    EntropyFunctor(double w) : weight(w) {}

    ResultType operator()(const InputType& x) const {
        typedef typename InputTraits::isScalar srcIsScalar;
        return entropy(x, srcIsScalar());
    }

protected:
    // Grayscale
    ResultType entropy(const InputType& x, VigraTrueType) const {
        return ResultTraits::fromRealPromote(weight * ResultTraits::toRealPromote(x));
    }

    // RGB
    ResultType entropy(const InputType& x, VigraFalseType) const {
        const typename ResultTraits::RealPromote minimum =
            ResultTraits::toRealPromote(std::min(std::min(x.red(), x.green()), x.blue()));
        return ResultTraits::fromRealPromote(weight * minimum);
    }

private:
    double weight;
};


template <typename ValueType>
struct MagnitudeAccessor
{
    typedef ValueType value_type;

    template <class Iterator>
    ValueType operator()(const Iterator& i) const {return std::abs(*i);}

    ValueType operator()(const ValueType* i) const {return std::abs(*i);}

    template <class Iterator, class Difference>
    ValueType operator()(const Iterator& i, Difference d) const {return std::abs(i[d]);}

    template <class Value, class Iterator>
    void set(const Value& v, const Iterator& i) const {
        *i = vigra::detail::RequiresExplicitCast<ValueType>::cast(std::abs(v));
    }

    template <class Value, class Iterator>
    void set(const Value& v, Iterator& i) const {
        *i = vigra::detail::RequiresExplicitCast<ValueType>::cast(std::abs(v));
    }

    template <class Value, class Iterator, class Difference>
    void set(const Value& v, const Iterator& i, const Difference& d) const {
        i[d] = vigra::detail::RequiresExplicitCast<ValueType>::cast(std::abs(v));
    }
};


template <typename InputType, typename ResultType>
class ClampingFunctor
{
public:
    typedef NumericTraits<InputType> InputTraits;

    ClampingFunctor(InputType lower, ResultType lowerValue,
                    InputType upper, ResultType upperValue) :
        lo(lower), up(upper), loval(lowerValue), upval(upperValue)
        {}

    ResultType operator()(const InputType& x) const {
        typedef typename InputTraits::isScalar srcIsScalar;
        return clamp(x, srcIsScalar());
    }

protected:
    // Grayscale
    ResultType clamp(const InputType& x, VigraTrueType) const {
        return x <= lo ? loval : (x >= up ? upval : x);
    }

    // RGB
    ResultType clamp(const InputType& x, VigraFalseType) const {
        return ResultType(x.red() <= lo.red() ?
                          loval.red() :
                          (x.red() >= up.red() ? upval.red() : x.red()),
                          x.green() <= lo.green() ?
                          loval.green() :
                          (x.green() >= up.green() ? upval.green() : x.green()),
                          x.red() <= lo.red() ?
                          loval.blue() :
                          (x.blue() >= up.blue() ? upval.blue() : x.blue()));
    }

private:
    InputType lo, up;
    ResultType loval, upval;
};


// If the first argument is lower than THRESHOLD return the second
// argument, i.e. the "fill-in" value multiplied with SCALE2,
// otherwise return the first argument multiplied with SCALE1.
template <typename InputType, typename ResultType>
class FillInFunctor
{
public:
    FillInFunctor(InputType thr, double s1, double s2) :
        threshold(thr), scale1(s1), scale2(s2)
        {}

    ResultType operator()(const InputType& x, const InputType& y) const {
        if (x >= threshold) return NumericTraits<ResultType>::fromRealPromote(scale1 * x);
        else return NumericTraits<ResultType>::fromRealPromote(scale2 * y);
    }

private:
    InputType threshold;
    double scale1, scale2;
};

template <typename ImageType, typename AlphaType, typename MaskType>
void enfuseMask(triple<typename ImageType::const_traverser, typename ImageType::const_traverser, typename ImageType::ConstAccessor> src,
                pair<typename AlphaType::const_traverser, typename AlphaType::ConstAccessor> mask,
                pair<typename MaskType::traverser, typename MaskType::Accessor> result) {
    typedef typename ImageType::value_type ImageValueType;
    typedef typename ImageType::PixelType PixelType;
    typedef typename NumericTraits<PixelType>::ValueType ScalarType;
    typedef typename MaskType::value_type MaskValueType;

    const typename ImageType::difference_type imageSize = src.second - src.first;

    // Exposure
    if (WExposure > 0.0) {
        typedef MultiGrayscaleAccessor<ImageValueType, ScalarType> MultiGrayAcc;
        MultiGrayAcc ga(GrayscaleProjector);
        ExposureFunctor<ImageValueType, MultiGrayAcc, MaskValueType> ef(WExposure, WMu, WSigma, ga);
        transformImageIfMP(src, mask, result, ef);
    }

    // Contrast
    if (WContrast > 0.0) {
        typedef typename NumericTraits<ScalarType>::Promote LongScalarType;
        typedef IMAGETYPE<LongScalarType> GradImage;
        typedef typename GradImage::iterator GradIterator;

        GradImage grad(imageSize);
        MultiGrayscaleAccessor<PixelType, LongScalarType> ga(GrayscaleProjector);

        if (FilterConfig.edgeScale > 0.0)
        {
#ifdef DEBUG_LOG
            cout << "+ Laplacian Edge Detection, scale = "
                 << FilterConfig.edgeScale << " pixels" << endl;
#endif
            GradImage laplacian(imageSize);

            if (FilterConfig.lceScale > 0.0)
            {
#ifdef DEBUG_LOG
                cout << "+ Local Contrast Enhancement, (scale, amount) = "
                     << FilterConfig.lceScale << " pixels, "
                     << (100.0 * FilterConfig.lceFactor) << "%" << endl;
#endif
                GradImage lce(imageSize);
                gaussianSharpening(src.first, src.second, ga,
                                   lce.upperLeft(), lce.accessor(),
                                   FilterConfig.lceFactor, FilterConfig.lceScale);
                laplacianOfGaussian(lce.upperLeft(), lce.lowerRight(), lce.accessor(),
                                    laplacian.upperLeft(), MagnitudeAccessor<LongScalarType>(),
                                    FilterConfig.edgeScale);
            }
            else
            {
                laplacianOfGaussian(src.first, src.second, ga,
                                    laplacian.upperLeft(), MagnitudeAccessor<LongScalarType>(),
                                    FilterConfig.edgeScale);
            }

#ifdef DEBUG_LOG
            {
                vigra::FindMinMax<LongScalarType> minmax;
                inspectImage(srcImageRange(laplacian), minmax);
                cout << "+ after Laplacian and Magnitude: min = " <<
                    minmax.min << ", max = " << minmax.max << endl;
            }
#endif

            const double minCurve =
                MinCurvature.isPercentage ?
                static_cast<double>(NumericTraits<ScalarType>::max()) * MinCurvature.value / 100.0 :
                MinCurvature.value;
            if (minCurve <= 0.0)
            {
#ifdef DEBUG_LOG
                cout << "+ truncate values below " << -minCurve << endl;;
#endif
                transformImageIfMP(laplacian.upperLeft(), laplacian.lowerRight(), laplacian.accessor(),
                                   mask.first, mask.second,
                                   grad.upperLeft(), grad.accessor(),
                                   ClampingFunctor<LongScalarType, LongScalarType>
                                   (static_cast<LongScalarType>(-minCurve), LongScalarType(),
                                    NumericTraits<LongScalarType>::max(), NumericTraits<LongScalarType>::max()));
            }
            else
            {
#ifdef DEBUG_LOG
                cout << "+ merge local contrast and edges - switch at " << minCurve << endl;
#endif
                GradImage localContrast(imageSize);
                // TODO: use localStdDev
                localStdDevIf(src.first, src.second, ga,
                              mask.first, mask.second,
                              localContrast.upperLeft(), localContrast.accessor(),
                              Size2D(ContrastWindowSize, ContrastWindowSize));

                combineTwoImagesIfMP(laplacian.upperLeft(), laplacian.lowerRight(), laplacian.accessor(),
                                     localContrast.upperLeft(), localContrast.accessor(),
                                     mask.first, mask.second,
                                     grad.upperLeft(), grad.accessor(),
                                     FillInFunctor<LongScalarType, LongScalarType>
                                     (static_cast<LongScalarType>(minCurve), // threshold
                                      1.0, // scale factor for "laplacian"
                                      minCurve / NumericTraits<ScalarType>::max())); // scale factor for "localContrast"
            }
        }
        else
        {
#ifdef DEBUG_LOG
            cout << "+ Variance of Local Contrast" << endl;
#endif
            localStdDevIf(src.first, src.second, ga,
                          mask.first, mask.second,
                          grad.upperLeft(), grad.accessor(),
                          Size2D(ContrastWindowSize, ContrastWindowSize));
        }

#ifdef DEBUG_LOG
        {
            vigra::FindMinMax<LongScalarType> minmax;
            inspectImage(srcImageRange(grad), minmax);
            cout << "+ final grad: min = " << minmax.min << ", max = " << minmax.max << endl;
        }
#endif
        ContrastFunctor<LongScalarType, ScalarType, MaskValueType> cf(WContrast);
        combineTwoImagesIfMP(srcImageRange(grad), result, mask, result,
                             const_parameters(bind(cf, _1) + _2));
    }

    // Saturation
    if (WSaturation > 0.0) {
        SaturationFunctor<ImageValueType, MaskValueType> sf(WSaturation);
        combineTwoImagesIfMP(src, result, mask, result,
                             const_parameters(bind(sf, _1) + _2));
    }

    // Entropy
    if (WEntropy > 0.0) {
        typedef typename ImageType::PixelType PixelType;
        typedef typename NumericTraits<PixelType>::ValueType ScalarType;
        typedef IMAGETYPE<PixelType> Image;
        Image entropy(imageSize);

        if (EntropyLowerCutoff.value > 0.0 ||
            (EntropyLowerCutoff.isPercentage && EntropyLowerCutoff.value < 100.0) ||
            (!EntropyLowerCutoff.isPercentage && EntropyUpperCutoff.value < NumericTraits<ScalarType>::max()))
        {
            const ScalarType lowerCutoff =
                EntropyLowerCutoff.isPercentage ?
                EntropyLowerCutoff.value *
                static_cast<double>(NumericTraits<ScalarType>::max()) /
                100.0 :
                EntropyLowerCutoff.value;
            const ScalarType upperCutoff =
                EntropyUpperCutoff.isPercentage ?
                EntropyUpperCutoff.value *
                static_cast<double>(NumericTraits<ScalarType>::max()) /
                100.0 :
                EntropyUpperCutoff.value;
#ifdef DEBUG_ENTROPY
            cout <<
                "+ EntropyLowerCutoff.value = " << EntropyLowerCutoff.value << ", " <<
                "lowerCutoff = " << static_cast<double>(lowerCutoff) << "\n" <<
                "+ EntropyUpperCutoff.value = " << EntropyUpperCutoff.value << ", " <<
                "upperCutoff = " << static_cast<double>(upperCutoff) << endl;
#endif
            Image trunc(imageSize);
            ClampingFunctor<PixelType, PixelType>
                cf(PixelType(lowerCutoff),
                   PixelType(ScalarType()),
                   PixelType(upperCutoff),
                   PixelType(NumericTraits<ScalarType>::max()));
            transformImageMP(src.first, src.second, src.third,
                             trunc.upperLeft(), trunc.accessor(),
                             cf);
            localEntropyIf(trunc.upperLeft(), trunc.lowerRight(), trunc.accessor(),
                           mask.first, mask.second,
                           entropy.upperLeft(), entropy.accessor(),
                           Size2D(EntropyWindowSize, EntropyWindowSize));
        }
        else
        {
            localEntropyIf(src.first, src.second, src.third,
                           mask.first, mask.second,
                           entropy.upperLeft(), entropy.accessor(),
                           Size2D(EntropyWindowSize, EntropyWindowSize));
        }

        EntropyFunctor<PixelType, MaskValueType> ef(WEntropy);
        combineTwoImagesIfMP(srcImageRange(entropy), result, mask, result,
                             const_parameters(bind(ef, _1) + _2));
    }
};


/** Enfuse's main blending loop. Templatized to handle different image types.
 */
template <typename ImagePixelType>
void enfuseMain(const list<char*>& anInputFileNameList,
                const list<ImageImportInfo*>& anImageInfoList,
                ImageExportInfo& anOutputImageInfo,
                Rect2D& anInputUnion)
{
    typedef typename EnblendNumericTraits<ImagePixelType>::ImagePixelComponentType ImagePixelComponentType;
    typedef typename EnblendNumericTraits<ImagePixelType>::ImageType ImageType;
    typedef typename EnblendNumericTraits<ImagePixelType>::AlphaPixelType AlphaPixelType;
    typedef typename EnblendNumericTraits<ImagePixelType>::AlphaType AlphaType;
    typedef IMAGETYPE<float> MaskType;
    typedef typename MaskType::value_type MaskPixelType;
    typedef typename EnblendNumericTraits<ImagePixelType>::ImagePyramidPixelType ImagePyramidPixelType;
    typedef typename EnblendNumericTraits<ImagePixelType>::ImagePyramidType ImagePyramidType;
    typedef typename EnblendNumericTraits<ImagePixelType>::MaskPyramidPixelType MaskPyramidPixelType;
    typedef typename EnblendNumericTraits<ImagePixelType>::MaskPyramidType MaskPyramidType;

    enum {ImagePyramidIntegerBits = EnblendNumericTraits<ImagePixelType>::ImagePyramidIntegerBits};
    enum {ImagePyramidFractionBits = EnblendNumericTraits<ImagePixelType>::ImagePyramidFractionBits};
    enum {MaskPyramidIntegerBits = EnblendNumericTraits<ImagePixelType>::MaskPyramidIntegerBits};
    enum {MaskPyramidFractionBits = EnblendNumericTraits<ImagePixelType>::MaskPyramidFractionBits};
    typedef typename EnblendNumericTraits<ImagePixelType>::SKIPSMImagePixelType SKIPSMImagePixelType;
    typedef typename EnblendNumericTraits<ImagePixelType>::SKIPSMAlphaPixelType SKIPSMAlphaPixelType;
    typedef typename EnblendNumericTraits<ImagePixelType>::SKIPSMMaskPixelType SKIPSMMaskPixelType;

    // List of input image / input alpha / mask triples
    list <triple<ImageType*, AlphaType*, MaskType*> > imageList;

    // Sum of all masks
    MaskType *normImage = new MaskType(anInputUnion.size());

    // Result image. Alpha will be union of all input alphas.
    pair<ImageType*, AlphaType*> outputPair(static_cast<ImageType*>(NULL),
                                            new AlphaType(anInputUnion.size()));
    list<ImageImportInfo*> imageInfoList(anImageInfoList);
    const unsigned numberOfImages = imageInfoList.size();

    unsigned m = 0;
    list<char*>::const_iterator inputFileNameIterator(anInputFileNameList.begin());
    while (!imageInfoList.empty()) {
        Rect2D imageBB;
        pair<ImageType*, AlphaType*> imagePair =
                assemble<ImageType, AlphaType>(imageInfoList, anInputUnion, imageBB);

        MaskType* mask = new MaskType(anInputUnion.size());

        enfuseMask<ImageType, AlphaType, MaskType>(srcImageRange(*(imagePair.first)),
                                                   srcImage(*(imagePair.second)),
                                                   destImage(*mask));

        if (SaveMasks) {
            const std::string maskFilename =
                enblend::expandFilenameTemplate(SoftMaskTemplate,
                                                numberOfImages,
                                                *inputFileNameIterator,
                                                OutputFileName,
                                                m);
            if (maskFilename == *inputFileNameIterator) {
                cerr << command
                     << ": will not overwrite input image \""
                     << *inputFileNameIterator
                     << "\" with soft mask file"
                     << endl;
                exit(1);
            } else if (maskFilename == OutputFileName) {
                cerr << command
                     << ": will not overwrite output image \""
                     << OutputFileName
                     << "\" with soft mask file"
                     << endl;
                exit(1);
            } else {
                if (Verbose > VERBOSE_MASK_MESSAGES) {
                    cerr << command
                         << ": info: saving soft mask \"" << maskFilename << "\"" << endl;
                }
                ImageExportInfo maskInfo(maskFilename.c_str());
                maskInfo.setXResolution(ImageResolution.x);
                maskInfo.setYResolution(ImageResolution.y);
                maskInfo.setCompression(MASK_COMPRESSION);
                exportImage(srcImageRange(*mask), maskInfo);
            }
        }

        // Make output alpha the union of all input alphas.
        copyImageIf(srcImageRange(*(imagePair.second)),
                    maskImage(*(imagePair.second)),
                    destImage(*(outputPair.second)));

        // Add the mask to the norm image.
        combineTwoImagesMP(srcImageRange(*mask),
                           srcImage(*normImage),
                           destImage(*normImage),
                           Arg1() + Arg2());

        imageList.push_back(make_triple(imagePair.first, imagePair.second, mask));

        #ifdef ENBLEND_CACHE_IMAGES
        if (Verbose > VERBOSE_CFI_MESSAGES) {
            CachedFileImageDirector& v = CachedFileImageDirector::v();
            cerr << command
                 << ": info: image cache statistics after loading image "
                 << m << "\n";
            v.printStats(cerr, command + ": info:     image", imagePair.first);
            v.printStats(cerr, command + ": info:     alpha", imagePair.second);
            v.printStats(cerr, command + ": info:     weight", mask);
            v.printStats(cerr, command + ": info:     normImage", normImage);
            v.printStats(cerr, command + ": info: ");
            v.resetCacheMisses();
        }
        #endif

        ++m;
        ++inputFileNameIterator;
    }

    const int totalImages = imageList.size();

    typename EnblendNumericTraits<ImagePixelType>::MaskPixelType maxMaskPixelType =
        NumericTraits<typename EnblendNumericTraits<ImagePixelType>::MaskPixelType>::max();

    if (UseHardMask) {
        if (Verbose > VERBOSE_MASK_MESSAGES) {
            cerr << command
                 << ": info: creating hard blend mask" << endl;
        }
        const Size2D sz = normImage->size();
        typename list< triple<ImageType*, AlphaType*, MaskType*> >::iterator imageIter;
#ifdef OPENMP
#pragma omp parallel for private (imageIter)
#endif
        for (int y = 0; y < sz.y; ++y) {
            for (int x = 0; x < sz.x; ++x) {
                float max = 0.0f;
                int maxi = 0;
                int i = 0;
                for (imageIter = imageList.begin();
                     imageIter != imageList.end();
                     ++imageIter) {
                    const float w = static_cast<float>((*imageIter->third)(x, y));
                    if (w > max) {
                        max = w;
                        maxi = i;
                    }
                    i++;
                }
                i = 0;
                for (imageIter = imageList.begin();
                     imageIter != imageList.end();
                     ++imageIter) {
                    if (max == 0.0f) {
                        (*imageIter->third)(x, y) =
                            static_cast<MaskPixelType>(maxMaskPixelType) / totalImages;
                    } else if (i == maxi) {
                        (*imageIter->third)(x, y) = maxMaskPixelType;
                    } else {
                        (*imageIter->third)(x, y) = 0.0f;
                    }
                    i++;
                }
            }
        }
        unsigned i = 0;
        if (SaveMasks) {
            for (imageIter = imageList.begin(), inputFileNameIterator = anInputFileNameList.begin();
                 imageIter != imageList.end();
                 ++imageIter, ++inputFileNameIterator) {
                const std::string maskFilename =
                    enblend::expandFilenameTemplate(HardMaskTemplate,
                                                    imageList.size(),
                                                    *inputFileNameIterator,
                                                    OutputFileName,
                                                    i);
                if (maskFilename == *inputFileNameIterator) {
                    cerr << command
                         << ": will not overwrite input image \""
                         << *inputFileNameIterator
                         << "\" with hard mask"
                         << endl;
                    exit(1);
                } else if (maskFilename == OutputFileName) {
                    cerr << command
                         << ": will not overwrite output image \""
                         << OutputFileName
                         << "\" with hard mask"
                         << endl;
                    exit(1);
                } else {
                    if (Verbose > VERBOSE_MASK_MESSAGES) {
                        cerr << command
                             << ": info: saving hard mask \"" << maskFilename << "\"" << endl;
                    }
                    ImageExportInfo maskInfo(maskFilename.c_str());
                    maskInfo.setXResolution(ImageResolution.x);
                    maskInfo.setYResolution(ImageResolution.y);
                    maskInfo.setCompression(MASK_COMPRESSION);
                    exportImage(srcImageRange(*(imageIter->third)), maskInfo);
                }
                i++;
            }
        }
        #ifdef ENBLEND_CACHE_IMAGES
        if (Verbose > VERBOSE_CFI_MESSAGES) {
            CachedFileImageDirector& v = CachedFileImageDirector::v();
            cerr << command
                 << ": info: image cache statistics after creating hard mask\n";
            v.printStats(cerr, command + ": info: ");
            v.resetCacheMisses();
        }
        #endif
    }

    Rect2D junkBB;
    const unsigned int numLevels =
        roiBounds<ImagePixelComponentType>(anInputUnion, anInputUnion, anInputUnion, anInputUnion,
                                           junkBB,
                                           WrapAround != OpenBoundaries);

    vector<ImagePyramidType*> *resultLP = NULL;

    m = 0;
    while (!imageList.empty()) {
        triple<ImageType*, AlphaType*, MaskType*> imageTriple = imageList.front();
        imageList.erase(imageList.begin());

        std::ostringstream oss0;
        oss0 << "imageGP" << m << "_";

        // imageLP is constructed using the image's own alpha channel
        // as the boundary for extrapolation.
        vector<ImagePyramidType*> *imageLP =
                laplacianPyramid<ImageType, AlphaType, ImagePyramidType,
                                 ImagePyramidIntegerBits, ImagePyramidFractionBits,
                                 SKIPSMImagePixelType, SKIPSMAlphaPixelType>(
                        oss0.str().c_str(),
                        numLevels, WrapAround != OpenBoundaries,
                        srcImageRange(*(imageTriple.first)),
                        maskImage(*(imageTriple.second)));

        delete imageTriple.first;
        delete imageTriple.second;

        //std::ostringstream oss1;
        //oss1 << "imageLP" << m << "_";
        //exportPyramid<ImagePyramidType>(imageLP, oss1.str().c_str());

        if (!UseHardMask) {
            // Normalize the mask coefficients.
            // Scale to the range expected by the MaskPyramidPixelType.
            combineTwoImagesMP(srcImageRange(*(imageTriple.third)),
                               srcImage(*normImage),
                               destImage(*(imageTriple.third)),
                               ifThenElse(Arg2() > Param(0.0),
                                          Param(maxMaskPixelType) * Arg1() / Arg2(),
                                          Param(maxMaskPixelType / totalImages)));
        }

        // maskGP is constructed using the union of the input alpha channels
        // as the boundary for extrapolation.
        vector<MaskPyramidType*> *maskGP =
            gaussianPyramid<MaskType, AlphaType, MaskPyramidType,
                            MaskPyramidIntegerBits, MaskPyramidFractionBits,
                            SKIPSMMaskPixelType, SKIPSMAlphaPixelType>
            (numLevels,
             WrapAround != OpenBoundaries,
             srcImageRange(*(imageTriple.third)),
             maskImage(*(outputPair.second)));

        delete imageTriple.third;

        //std::ostringstream oss2;
        //oss2 << "maskGP" << m << "_";
        //exportPyramid<MaskPyramidType>(maskGP, oss2.str().c_str());

        ConvertScalarToPyramidFunctor<typename EnblendNumericTraits<ImagePixelType>::MaskPixelType,
                                      MaskPyramidPixelType,
                                      MaskPyramidIntegerBits,
                                      MaskPyramidFractionBits> maskConvertFunctor;
        MaskPyramidPixelType maxMaskPyramidPixelValue = maskConvertFunctor(maxMaskPixelType);

        for (unsigned int i = 0; i < maskGP->size(); ++i) {
            // Multiply image lp with the mask gp.
            combineTwoImagesMP(srcImageRange(*((*imageLP)[i])),
                               srcImage(*((*maskGP)[i])),
                               destImage(*((*imageLP)[i])),
                               ImageMaskMultiplyFunctor<MaskPyramidPixelType>(maxMaskPyramidPixelValue));

            // Done with maskGP.
            delete (*maskGP)[i];
        }
        delete maskGP;

        //std::ostringstream oss3;
        //oss3 << "multLP" << m << "_";
        //exportPyramid<ImagePyramidType>(imageLP, oss3.str().c_str());

        if (resultLP != NULL) {
            // Add imageLP to resultLP.
            for (unsigned int i = 0; i < imageLP->size(); ++i) {
                combineTwoImagesMP(srcImageRange(*((*imageLP)[i])),
                                   srcImage(*((*resultLP)[i])),
                                   destImage(*((*resultLP)[i])),
                                   Arg1() + Arg2());
                delete (*imageLP)[i];
            }
            delete imageLP;
        }
        else {
            resultLP = imageLP;
        }

        //std::ostringstream oss4;
        //oss4 << "resultLP" << m << "_";
        //exportPyramid<ImagePyramidType>(resultLP, oss4.str().c_str());

        ++m;
    }

    delete normImage;

    //exportPyramid<ImagePyramidType>(resultLP, "resultLP");

    collapsePyramid<SKIPSMImagePixelType>(WrapAround != OpenBoundaries, resultLP);

    outputPair.first = new ImageType(anInputUnion.size());

    copyFromPyramidImageIf<ImagePyramidType, AlphaType, ImageType,
                           ImagePyramidIntegerBits, ImagePyramidFractionBits>(
            srcImageRange(*((*resultLP)[0])),
            maskImage(*(outputPair.second)),
            destImage(*(outputPair.first)));

    // Delete result pyramid.
    for (unsigned int i = 0; i < resultLP->size(); ++i) {
        delete (*resultLP)[i];
    }
    delete resultLP;

    checkpoint(outputPair, anOutputImageInfo);

    delete outputPair.first;
    delete outputPair.second;

};

} // namespace enblend

#endif /* __ENFUSE_H__ */

// Local Variables:
// mode: c++
// End: