File: antsMotionCorr.cxx

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

#include "itkAffineTransform.h"
#include "itkBSplineTransform.h"
#include "itkBSplineSmoothingOnUpdateDisplacementFieldTransform.h"
#include "itkCompositeTransform.h"
#include "itkGaussianSmoothingOnUpdateDisplacementFieldTransform.h"
#include "itkIdentityTransform.h"
#include "itkEuler2DTransform.h"
#include "itkEuler3DTransform.h"
#include "itkTransform.h"
#include "itkExtractImageFilter.h"

#include "itkBSplineTransformParametersAdaptor.h"
#include "itkBSplineSmoothingOnUpdateDisplacementFieldTransformParametersAdaptor.h"
#include "itkGaussianSmoothingOnUpdateDisplacementFieldTransformParametersAdaptor.h"
#include "itkTimeVaryingVelocityFieldTransformParametersAdaptor.h"

#include "itkGradientDescentOptimizerv4.h"
#include "itkConjugateGradientLineSearchOptimizerv4.h"
#include "itkQuasiNewtonOptimizerv4.h"

#include "itkHistogramMatchingImageFilter.h"
#include "itkMinimumMaximumImageCalculator.h"
#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkMacro.h"
#include "itkRegistrationParameterScalesFromPhysicalShift.h"
#include "itkResampleImageFilter.h"
#include "itkShrinkImageFilter.h"
#include "itkTimeProbe.h"
#include "itkTransformFileReader.h"
#include "itkTransformFileWriter.h"
#include "itkSimilarity2DTransform.h"
#include "itkSimilarity3DTransform.h"

// Headers for interpolating functions (to support the --interpolation choice)
#include "itkBSplineInterpolateImageFunction.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkInterpolateImageFunction.h"
#include "itkNearestNeighborInterpolateImageFunction.h"
#include "itkWindowedSincInterpolateImageFunction.h"

#include <sstream>

namespace ants
{
/** \class antsRegistrationCommandIterationUpdate
 *  \brief change parameters between iterations of registration
 */
template <typename TFilter>
class antsRegistrationCommandIterationUpdate : public itk::Command
{
public:
  using Self = antsRegistrationCommandIterationUpdate<TFilter>;
  using Superclass = itk::Command;
  using Pointer = itk::SmartPointer<Self>;
  itkNewMacro(Self);

protected:
  antsRegistrationCommandIterationUpdate() { this->m_LogStream = &std::cout; }

public:
  void
  Execute(itk::Object * caller, const itk::EventObject & event) override
  {
    Execute((const itk::Object *)caller, event);
  }

  void
  Execute(const itk::Object * object, const itk::EventObject & event) override
  {
    auto * filter = const_cast<TFilter *>(dynamic_cast<const TFilter *>(object));

    unsigned int currentLevel = 0;

    if (typeid(event) == typeid(itk::IterationEvent))
    {
      currentLevel = filter->GetCurrentLevel() + 1;
    }
    if (currentLevel < this->m_NumberOfIterations.size())
    {
      typename TFilter::ShrinkFactorsPerDimensionContainerType shrinkFactors =
        filter->GetShrinkFactorsPerDimension(currentLevel);
      typename TFilter::SmoothingSigmasArrayType                 smoothingSigmas = filter->GetSmoothingSigmasPerLevel();
      typename TFilter::TransformParametersAdaptorsContainerType adaptors =
        filter->GetTransformParametersAdaptorsPerLevel();

      this->Logger() << "  Current level = " << currentLevel << std::endl;
      this->Logger() << "    number of iterations = " << this->m_NumberOfIterations[currentLevel] << std::endl;
      this->Logger() << "    shrink factors = " << shrinkFactors << std::endl;
      this->Logger() << "    smoothing sigmas = " << smoothingSigmas[currentLevel] << std::endl;
      this->Logger() << "    required fixed parameters = " << adaptors[currentLevel]->GetRequiredFixedParameters()
                     << std::endl;

      using GradientDescentOptimizerType = itk::ConjugateGradientLineSearchOptimizerv4;
      auto * optimizer = reinterpret_cast<GradientDescentOptimizerType *>(filter->GetModifiableOptimizer());
      optimizer->SetNumberOfIterations(this->m_NumberOfIterations[currentLevel]);
      optimizer->SetMinimumConvergenceValue(1.e-7);
      optimizer->SetConvergenceWindowSize(10);
      optimizer->SetLowerLimit(0);
      optimizer->SetUpperLimit(2);
      optimizer->SetEpsilon(0.1);
    }
  }

  void
  SetNumberOfIterations(const std::vector<unsigned int> & iterations)
  {
    this->m_NumberOfIterations = iterations;
  }

  void
  SetLogStream(std::ostream & logStream)
  {
    this->m_LogStream = &logStream;
  }

private:
  std::ostream &
  Logger() const
  {
    return *m_LogStream;
  }

  std::vector<unsigned int> m_NumberOfIterations;
  std::ostream *            m_LogStream;
};

template <typename T>
inline std::string
ants_moco_to_string(const T & t)
{
  std::stringstream ss;

  ss << t;
  return ss.str();
}

template <typename ImageType>
typename ImageType::Pointer
PreprocessImage(ImageType *                   inputImage,
                typename ImageType::PixelType lowerScaleFunction,
                typename ImageType::PixelType upperScaleFunction,
                float                         winsorizeLowerQuantile,
                float                         winsorizeUpperQuantile,
                ImageType *                   histogramMatchSourceImage = nullptr)
{
  bool verbose = false;
  using HistogramFilterType = itk::Statistics::ImageToHistogramFilter<ImageType>;
  using InputBooleanObjectType = typename HistogramFilterType::InputBooleanObjectType;
  using HistogramSizeType = typename HistogramFilterType::HistogramSizeType;

  HistogramSizeType histogramSize(1);
  histogramSize[0] = 256;

  typename InputBooleanObjectType::Pointer autoMinMaxInputObject = InputBooleanObjectType::New();
  autoMinMaxInputObject->Set(true);

  typename HistogramFilterType::Pointer histogramFilter = HistogramFilterType::New();
  histogramFilter->SetInput(inputImage);
  histogramFilter->SetAutoMinimumMaximumInput(autoMinMaxInputObject);
  histogramFilter->SetHistogramSize(histogramSize);
  histogramFilter->SetMarginalScale(10.0);
  histogramFilter->Update();

  float lowerFunction = histogramFilter->GetOutput()->Quantile(0, winsorizeLowerQuantile);
  float upperFunction = histogramFilter->GetOutput()->Quantile(0, winsorizeUpperQuantile);
  using IntensityWindowingImageFilterType = itk::IntensityWindowingImageFilter<ImageType, ImageType>;

  typename IntensityWindowingImageFilterType::Pointer windowingFilter = IntensityWindowingImageFilterType::New();
  windowingFilter->SetInput(inputImage);
  windowingFilter->SetWindowMinimum(lowerFunction);
  windowingFilter->SetWindowMaximum(upperFunction);
  windowingFilter->SetOutputMinimum(lowerScaleFunction);
  windowingFilter->SetOutputMaximum(upperScaleFunction);
  windowingFilter->Update();

  typename ImageType::Pointer outputImage = nullptr;
  if (histogramMatchSourceImage)
  {
    using HistogramMatchingFilterType = itk::HistogramMatchingImageFilter<ImageType, ImageType>;
    typename HistogramMatchingFilterType::Pointer matchingFilter = HistogramMatchingFilterType::New();
    matchingFilter->SetInput(windowingFilter->GetOutput());
    matchingFilter->SetReferenceImage(histogramMatchSourceImage);
    matchingFilter->SetNumberOfHistogramLevels(256);
    matchingFilter->SetNumberOfMatchPoints(12);
    matchingFilter->ThresholdAtMeanIntensityOn();
    matchingFilter->Update();

    outputImage = matchingFilter->GetOutput();
    outputImage->Update();
    outputImage->DisconnectPipeline();

    using CalculatorType = itk::MinimumMaximumImageCalculator<ImageType>;
    typename CalculatorType::Pointer calc = CalculatorType::New();
    calc->SetImage(inputImage);
    calc->ComputeMaximum();
    calc->ComputeMinimum();
    if (itk::Math::abs(calc->GetMaximum() - calc->GetMinimum()) < static_cast<typename ImageType::PixelType>(1.e-9))
    {
      if (verbose)
        std::cout << "Warning: bad time point - too little intensity variation" << std::endl;
      return histogramMatchSourceImage;
    }
  }
  else
  {
    outputImage = windowingFilter->GetOutput();
    outputImage->Update();
    outputImage->DisconnectPipeline();
  }
  return outputImage;
}

template <typename T>
struct ants_moco_index_cmp
{
  ants_moco_index_cmp(const T _arr)
    : arr(_arr)
  {}

  bool
  operator()(const size_t a, const size_t b) const
  {
    return arr[a] < arr[b];
  }

  const T arr;
};

template <typename TFilter>
class CommandIterationUpdate final : public itk::Command
{
public:
  using Self = CommandIterationUpdate<TFilter>;
  using Superclass = itk::Command;
  using Pointer = itk::SmartPointer<Self>;
  itkNewMacro(Self);

protected:
  CommandIterationUpdate() = default;

public:
  void
  Execute(itk::Object * caller, const itk::EventObject & event) override
  {
    Execute((const itk::Object *)caller, event);
  }

  void
  Execute(const itk::Object * object, const itk::EventObject & event) override
  {
    bool   verbose = false;
    auto * filter = const_cast<TFilter *>(dynamic_cast<const TFilter *>(object));

    if (typeid(event) != typeid(itk::IterationEvent))
    {
      return;
    }

    unsigned int                                             currentLevel = filter->GetCurrentLevel();
    typename TFilter::ShrinkFactorsPerDimensionContainerType shrinkFactors =
      filter->GetShrinkFactorsPerDimension(currentLevel);
    typename TFilter::SmoothingSigmasArrayType                 smoothingSigmas = filter->GetSmoothingSigmasPerLevel();
    typename TFilter::TransformParametersAdaptorsContainerType adaptors =
      filter->GetTransformParametersAdaptorsPerLevel();

    if (verbose)
      std::cout << "  Current level = " << currentLevel << std::endl;
    if (verbose)
      std::cout << "    number of iterations = " << this->m_NumberOfIterations[currentLevel] << std::endl;
    if (verbose)
      std::cout << "    shrink factor = " << shrinkFactors[currentLevel] << std::endl;
    if (verbose)
      std::cout << "    smoothing sigma = " << smoothingSigmas[currentLevel] << std::endl;
    if (verbose)
      std::cout << "    required fixed parameters = " << adaptors[currentLevel]->GetRequiredFixedParameters()
                << std::endl;

    using OptimizerType = itk::ConjugateGradientLineSearchOptimizerv4;
    auto * optimizer = reinterpret_cast<OptimizerType *>(filter->GetModifiableOptimizer());
    optimizer->SetNumberOfIterations(this->m_NumberOfIterations[currentLevel]);
    optimizer->SetMinimumConvergenceValue(1.e-7);
    optimizer->SetConvergenceWindowSize(10);
    optimizer->SetLowerLimit(0);
    optimizer->SetUpperLimit(2);
    optimizer->SetEpsilon(0.1);
  }

  void
  SetNumberOfIterations(std::vector<unsigned int> iterations)
  {
    this->m_NumberOfIterations = iterations;
  }

private:
  std::vector<unsigned int> m_NumberOfIterations;
};

// Transform traits to generalize the rigid transform
//
template <unsigned int ImageDimension>
class RigidTransformTraits
{
  // Don't worry about the fact that the default option is the
  // affine Transform, that one will not actually be instantiated.
public:
  using TransformType = itk::AffineTransform<double, ImageDimension>;
};

template <>
class RigidTransformTraits<2>
{
public:
  using TransformType = itk::Euler2DTransform<double>;
};

template <>
class RigidTransformTraits<3>
{
public:
  // typedef itk::VersorRigid3DTransform<double> TransformType;
  // typedef itk::QuaternionRigidTransform<double>  TransformType;
  using TransformType = itk::Euler3DTransform<double>;
};

template <unsigned int ImageDimension>
class SimilarityTransformTraits
{
  // Don't worry about the fact that the default option is the
  // affine Transform, that one will not actually be instantiated.
public:
  using TransformType = itk::AffineTransform<double, ImageDimension>;
};

template <>
class SimilarityTransformTraits<2>
{
public:
  using TransformType = itk::Similarity2DTransform<double>;
};

template <>
class SimilarityTransformTraits<3>
{
public:
  using TransformType = itk::Similarity3DTransform<double>;
};

/*
template <unsigned int ImageDimension>
class CompositeAffineTransformTraits
{
// Don't worry about the fact that the default option is the
// affine Transform, that one will not actually be instantiated.
public:
  typedef itk::AffineTransform<double, ImageDimension> TransformType;
};
template <>
class CompositeAffineTransformTraits<2>
{
public:
  typedef itk::ANTSCenteredAffine2DTransform<double> TransformType;
};
template <>
class CompositeAffineTransformTraits<3>
{
public:
  typedef itk::ANTSAffine3DTransform<double> TransformType;
};
*/

template <typename TImageIn, typename TImageOut>
void
AverageTimeImages(typename TImageIn::Pointer  image_in,
                  typename TImageOut::Pointer image_avg,
                  std::vector<unsigned int>   timelist)
{
  bool verbose = false;
  using ImageType = TImageIn;
  using OutImageType = TImageOut;
  enum
  {
    ImageDimension = ImageType::ImageDimension
  };
  using Iterator = itk::ImageRegionIteratorWithIndex<OutImageType>;
  image_avg->FillBuffer(0);
  unsigned int timedims = image_in->GetLargestPossibleRegion().GetSize()[ImageDimension - 1];
  if (timelist.empty())
  {
    for (unsigned int timedim = 0; timedim < timedims; timedim++)
    {
      timelist.push_back(timedim);
    }
  }
  if (verbose)
    std::cout << " averaging with " << timelist.size() << " images of " << timedims << " timedims " << std::endl;
  Iterator vfIter2(image_avg, image_avg->GetLargestPossibleRegion());
  for (vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2)
  {
    typename OutImageType::PixelType fval = 0;
    typename ImageType::IndexType    ind;
    typename OutImageType::IndexType spind = vfIter2.GetIndex();
    for (unsigned int & xx : timelist)
    {
      for (unsigned int yy = 0; yy < ImageDimension - 1; yy++)
      {
        ind[yy] = spind[yy];
      }
      ind[ImageDimension - 1] = xx;
      fval += image_in->GetPixel(ind);
    }
    fval /= static_cast<typename OutImageType::PixelType>(timelist.size());
    image_avg->SetPixel(spind, fval);
  }
  if (verbose)
    std::cout << " averaging images done " << std::endl;
}

template <unsigned int ImageDimension>
int
ants_motion(itk::ants::CommandLineParser * parser)
{
  unsigned int                                      verbose = 0;
  itk::ants::CommandLineParser::OptionType::Pointer vOption = parser->GetOption("verbose");
  if (vOption && vOption->GetNumberOfFunctions())
  {
    verbose = parser->Convert<unsigned int>(vOption->GetFunction(0)->GetName());
  }
  if (verbose)
    std::cout << " verbose " << std::endl;
  // We infer the number of stages by the number of transformations
  // specified by the user which should match the number of metrics.
  unsigned numberOfStages = 0;

  using PixelType = float;
  using RealType = double;
  using FixedIOImageType = itk::Image<PixelType, ImageDimension>;
  using FixedImageType = itk::Image<PixelType, ImageDimension>;
  using MovingIOImageType = itk::Image<PixelType, ImageDimension + 1>;
  using MovingImageType = itk::Image<PixelType, ImageDimension + 1>;
  using VectorIOType = itk::Vector<RealType, ImageDimension + 1>;
  using DisplacementIOFieldType = itk::Image<VectorIOType, ImageDimension + 1>;
  using VectorType = itk::Vector<RealType, ImageDimension>;
  using DisplacementFieldType = itk::Image<VectorType, ImageDimension>;
  using vMatrix = vnl_matrix<RealType>;
  vMatrix param_values;
  using CompositeTransformType = itk::CompositeTransform<RealType, ImageDimension>;
  std::vector<typename CompositeTransformType::Pointer> CompositeTransformVector;
  using OptionType = typename itk::ants::CommandLineParser::OptionType;

  typename OptionType::Pointer averageOption = parser->GetOption("average-image");
  if (averageOption && averageOption->GetNumberOfFunctions())
  {
    typename OptionType::Pointer outputOption = parser->GetOption("output");
    if (!outputOption)
    {
      std::cerr << "Output option not specified.  Should be the output average image name." << std::endl;
      return EXIT_FAILURE;
    }
    std::string outputPrefix = outputOption->GetFunction(0)->GetParameter(0);
    if (outputPrefix.length() < 3)
    {
      outputPrefix = outputOption->GetFunction(0)->GetName();
    }
    std::string                         fn = averageOption->GetFunction(0)->GetName();
    typename MovingIOImageType::Pointer movingImage;
    ReadImage<MovingIOImageType>(movingImage, fn.c_str());
    typename FixedIOImageType::Pointer avgImage;
    using ExtractFilterType = itk::ExtractImageFilter<MovingIOImageType, FixedIOImageType>;
    typename MovingIOImageType::RegionType extractRegion = movingImage->GetLargestPossibleRegion();
    extractRegion.SetSize(ImageDimension, 0);
    typename ExtractFilterType::Pointer extractFilter = ExtractFilterType::New();
    extractFilter->SetInput(movingImage);
    extractFilter->SetDirectionCollapseToSubmatrix();
    if (ImageDimension == 2)
    {
      extractFilter->SetDirectionCollapseToIdentity();
    }
    unsigned int td = 0;
    extractRegion.SetIndex(ImageDimension, td);
    extractFilter->SetExtractionRegion(extractRegion);
    extractFilter->Update();
    avgImage = extractFilter->GetOutput();
    std::vector<unsigned int> timelist;
    AverageTimeImages<MovingIOImageType, FixedIOImageType>(movingImage, avgImage, timelist);
    if (verbose)
      std::cout << "average out " << outputPrefix << std::endl;
    ANTs::WriteImage<FixedIOImageType>(avgImage, outputPrefix.c_str());
    return EXIT_SUCCESS;
  }

  typename OptionType::Pointer transformOption = parser->GetOption("transform");
  if (transformOption && transformOption->GetNumberOfFunctions())
  {
    numberOfStages = transformOption->GetNumberOfFunctions();
  }
  else
  {
    std::cerr << "No transformations are specified." << std::endl;
    return EXIT_FAILURE;
  }

  if (verbose)
    std::cout << "Registration using " << numberOfStages << " total stages." << std::endl;

  // Get the interpolator and possible parameters
  std::string                  whichInterpolator("linear");
  typename OptionType::Pointer interpolationOption = parser->GetOption("interpolation");
  if (interpolationOption && interpolationOption->GetNumberOfFunctions())
  {
    whichInterpolator = interpolationOption->GetFunction(0)->GetName();
    ConvertToLowerCase(whichInterpolator);
  }

  using ImageType = itk::Image<PixelType, ImageDimension>; // Used only for templating interp functions
  using InterpolatorType = itk::InterpolateImageFunction<ImageType, RealType>;
  typename InterpolatorType::Pointer interpolator = nullptr;

  if (!std::strcmp(whichInterpolator.c_str(), "linear"))
  {
    using LinearInterpolatorType = itk::LinearInterpolateImageFunction<ImageType, RealType>;
    typename LinearInterpolatorType::Pointer linearInterpolator = LinearInterpolatorType::New();
    interpolator = linearInterpolator;
  }
  else if (!std::strcmp(whichInterpolator.c_str(), "nearestneighbor"))
  {
    using NearestNeighborInterpolatorType = itk::NearestNeighborInterpolateImageFunction<ImageType, RealType>;
    typename NearestNeighborInterpolatorType::Pointer nearestNeighborInterpolator =
      NearestNeighborInterpolatorType::New();
    interpolator = nearestNeighborInterpolator;
  }
  else if (!std::strcmp(whichInterpolator.c_str(), "bspline"))
  {
    using BSplineInterpolatorType = itk::BSplineInterpolateImageFunction<ImageType, RealType>;
    typename BSplineInterpolatorType::Pointer bSplineInterpolator = BSplineInterpolatorType::New();
    if (interpolationOption->GetFunction(0)->GetNumberOfParameters() > 0)
    {
      auto bsplineOrder = parser->Convert<unsigned int>(interpolationOption->GetFunction(0)->GetParameter(0));
      bSplineInterpolator->SetSplineOrder(bsplineOrder);
    }
    interpolator = bSplineInterpolator;
  }
  else if (!std::strcmp(whichInterpolator.c_str(), "CosineWindowedSinc"))
  {
    using CosineInterpolatorType =
      itk::WindowedSincInterpolateImageFunction<ImageType,
                                                3,
                                                itk::Function::CosineWindowFunction<3, RealType, RealType>,
                                                itk::ConstantBoundaryCondition<ImageType>,
                                                RealType>;
    typename CosineInterpolatorType::Pointer cosineInterpolator = CosineInterpolatorType::New();
    interpolator = cosineInterpolator;
  }
  else if (!std::strcmp(whichInterpolator.c_str(), "hammingwindowedsinc"))
  {
    using HammingInterpolatorType =
      itk::WindowedSincInterpolateImageFunction<ImageType,
                                                3,
                                                itk::Function::HammingWindowFunction<3, RealType, RealType>,
                                                itk::ConstantBoundaryCondition<ImageType>,
                                                RealType>;
    typename HammingInterpolatorType::Pointer hammingInterpolator = HammingInterpolatorType::New();
    interpolator = hammingInterpolator;
  }
  else if (!std::strcmp(whichInterpolator.c_str(), "lanczoswindowedsinc"))
  {
    using LanczosInterpolatorType =
      itk::WindowedSincInterpolateImageFunction<ImageType,
                                                3,
                                                itk::Function::LanczosWindowFunction<3, RealType, RealType>,
                                                itk::ConstantBoundaryCondition<ImageType>,
                                                RealType>;
    typename LanczosInterpolatorType::Pointer lanczosInterpolator = LanczosInterpolatorType::New();
    interpolator = lanczosInterpolator;
  }
  else if (!std::strcmp(whichInterpolator.c_str(), "blackmanwindowedsinc"))
  {
    using BlackmanInterpolatorType =
      itk::WindowedSincInterpolateImageFunction<ImageType,
                                                3,
                                                itk::Function::BlackmanWindowFunction<3, RealType, RealType>,
                                                itk::ConstantBoundaryCondition<ImageType>,
                                                RealType>;
    typename BlackmanInterpolatorType::Pointer blackmanInterpolator = BlackmanInterpolatorType::New();
    interpolator = blackmanInterpolator;
  }
  else if (!std::strcmp(whichInterpolator.c_str(), "welchwindowedsinc"))
  {
    using WelchInterpolatorType =
      itk::WindowedSincInterpolateImageFunction<ImageType,
                                                3,
                                                itk::Function::WelchWindowFunction<3, RealType, RealType>,
                                                itk::ConstantBoundaryCondition<ImageType>,
                                                RealType>;
    typename WelchInterpolatorType::Pointer welchInterpolator = WelchInterpolatorType::New();
    interpolator = welchInterpolator;
  }

  typename OptionType::Pointer metricOption = parser->GetOption("metric");
  if (!metricOption || metricOption->GetNumberOfFunctions() != numberOfStages)
  {
    std::cerr << "The number of metrics specified does not match the number of stages." << std::endl;
    return EXIT_FAILURE;
  }

  typename OptionType::Pointer iterationsOption = parser->GetOption("iterations");
  if (!iterationsOption || iterationsOption->GetNumberOfFunctions() != numberOfStages)
  {
    std::cerr << "The number of iteration sets specified does not match the number of stages." << std::endl;
    return EXIT_FAILURE;
  }

  typename OptionType::Pointer shrinkFactorsOption = parser->GetOption("shrinkFactors");
  if (!shrinkFactorsOption || shrinkFactorsOption->GetNumberOfFunctions() != numberOfStages)
  {
    std::cerr << "The number of shrinkFactor sets specified does not match the number of stages." << std::endl;
    return EXIT_FAILURE;
  }

  typename OptionType::Pointer smoothingSigmasOption = parser->GetOption("smoothingSigmas");
  if (!smoothingSigmasOption || smoothingSigmasOption->GetNumberOfFunctions() != numberOfStages)
  {
    std::cerr << "The number of smoothing sigma sets specified does not match the number of stages." << std::endl;
    return EXIT_FAILURE;
  }

  typename OptionType::Pointer outputOption = parser->GetOption("output");
  if (!outputOption)
  {
    std::cerr << "Output option not specified." << std::endl;
    return EXIT_FAILURE;
  }
  std::string outputPrefix = outputOption->GetFunction(0)->GetParameter(0);
  if (outputPrefix.length() < 3)
  {
    outputPrefix = outputOption->GetFunction(0)->GetName();
  }

  unsigned int                                      nimagestoavg = 0;
  itk::ants::CommandLineParser::OptionType::Pointer navgOption = parser->GetOption("n-images");
  if (navgOption && navgOption->GetNumberOfFunctions())
  {
    nimagestoavg = parser->Convert<unsigned int>(navgOption->GetFunction(0)->GetName());
    if (verbose)
      std::cout << " nimagestoavg " << nimagestoavg << std::endl;
  }

  unsigned int                                      writeDisplacementField = 0;
  itk::ants::CommandLineParser::OptionType::Pointer wdopt = parser->GetOption("write-displacement");
  if (wdopt && wdopt->GetNumberOfFunctions())
  {
    writeDisplacementField = parser->Convert<unsigned int>(wdopt->GetFunction(0)->GetName());
  }

  bool                doEstimateLearningRateOnce(false);
  // OptionType::Pointer rateOption = parser->GetOption("use-estimate-learning-rate-once");
  // if (rateOption && rateOption->GetNumberOfFunctions())
  // {
  //   std::string rateFunction = rateOption->GetFunction(0)->GetName();
  //   ConvertToLowerCase(rateFunction);
  //   if (rateFunction.compare("1") == 0 || rateFunction.compare("true") == 0)
  //   {
  //     doEstimateLearningRateOnce = true;
  //   }
  // }

  bool                doHistogramMatch(true);
  OptionType::Pointer histogramMatchOption = parser->GetOption("use-histogram-matching");
  if (histogramMatchOption && histogramMatchOption->GetNumberOfFunctions())
  {
    std::string histogramMatchFunction = histogramMatchOption->GetFunction(0)->GetName();
    ConvertToLowerCase(histogramMatchFunction);
    if (histogramMatchFunction.compare("0") == 0 || histogramMatchFunction.compare("false") == 0)
    {
      doHistogramMatch = false;
    }
  }

  // Zero seed means use default behavior: registration randomizer seeds from system time
  // and does not re-seed iterator
  int antsRandomSeed = 0;

  itk::ants::CommandLineParser::OptionType::Pointer randomSeedOption = parser->GetOption("random-seed");
  if (randomSeedOption && randomSeedOption->GetNumberOfFunctions())
  {
    antsRandomSeed = parser->Convert<int>(randomSeedOption->GetFunction(0)->GetName());
  }
  else
  {
    char * envSeed = getenv("ANTS_RANDOM_SEED");

    if (envSeed != nullptr)
    {
      antsRandomSeed = std::stoi(envSeed);
    }
  }

  unsigned int   nparams = 2;
  itk::TimeProbe totalTimer;
  totalTimer.Start();
  double metricmean = 0;

  using AffineTransformType = itk::AffineTransform<RealType, ImageDimension>;
  using AffineRegistrationType = itk::ImageRegistrationMethodv4<FixedImageType, FixedImageType, AffineTransformType>;
  // We iterate backwards because the command line options are stored as a stack (first in last out)
  typename DisplacementIOFieldType::Pointer displacementout = nullptr;
  typename DisplacementIOFieldType::Pointer displacementinv = nullptr;

  for (int currentStage = numberOfStages - 1; currentStage >= 0; currentStage--)
  {
    if (verbose)
      std::cout << std::endl << "Stage " << numberOfStages - currentStage << std::endl;
    std::stringstream currentStageString;
    currentStageString << currentStage;

    // Get the fixed and moving images

    std::string fixedImageFileName = metricOption->GetFunction(currentStage)->GetParameter(0);
    std::string movingImageFileName = metricOption->GetFunction(currentStage)->GetParameter(1);
    if (verbose)
      std::cout << "  fixed image: " << fixedImageFileName << std::endl;
    if (verbose)
      std::cout << "  moving image: " << movingImageFileName << std::endl;
    typename FixedImageType::Pointer   fixed_time_slice = nullptr;
    typename FixedImageType::Pointer   moving_time_slice = nullptr;
    typename FixedIOImageType::Pointer fixedInImage;
    ReadImage<FixedIOImageType>(fixedInImage, fixedImageFileName.c_str());
    fixedInImage->Update();
    fixedInImage->DisconnectPipeline();
    typename FixedImageType::Pointer fixedImage;
    fixedImage = arCastImage<FixedIOImageType, FixedImageType>(fixedInImage);

    typename MovingIOImageType::Pointer movingInImage;
    typename MovingImageType::Pointer   movingImage;
    ReadImage<MovingIOImageType>(movingInImage, movingImageFileName.c_str());
    movingInImage->Update();
    movingInImage->DisconnectPipeline();
    movingImage = arCastImage<MovingIOImageType, MovingImageType>(movingInImage);
    unsigned int timedims = movingImage->GetLargestPossibleRegion().GetSize()[ImageDimension];

    typename MovingIOImageType::Pointer       outputImage = MovingIOImageType::New();
    typename MovingIOImageType::RegionType    outRegion;
    typename MovingIOImageType::SizeType      outSize;
    typename MovingIOImageType::SpacingType   outSpacing;
    typename MovingIOImageType::PointType     outOrigin;
    typename MovingIOImageType::DirectionType outDirection;
    for (unsigned int d = 0; d < ImageDimension; d++)
    {
      outSize[d] = fixedImage->GetLargestPossibleRegion().GetSize()[d];
      outSpacing[d] = fixedImage->GetSpacing()[d];
      outOrigin[d] = fixedImage->GetOrigin()[d];
      for (unsigned int e = 0; e < ImageDimension; e++)
      {
        outDirection(e, d) = fixedImage->GetDirection()(e, d);
      }
    }
    for (unsigned int d = 0; d < ImageDimension; d++)
    {
      outDirection(d, ImageDimension) = 0;
      outDirection(ImageDimension, d) = 0;
    }
    outDirection(ImageDimension, ImageDimension) = 1.0;

    outSize[ImageDimension] = timedims;
    outSpacing[ImageDimension] = movingImage->GetSpacing()[ImageDimension];
    outOrigin[ImageDimension] = movingImage->GetOrigin()[ImageDimension];

    outRegion.SetSize(outSize);
    outputImage->SetRegions(outRegion);
    outputImage->SetSpacing(outSpacing);
    outputImage->SetOrigin(outOrigin);
    outputImage->SetDirection(outDirection);
    outputImage->AllocateInitialized();


    if (writeDisplacementField > 0)
    {
      /** Handle all output: images and displacement fields */
      using IdentityIOTransformType = itk::IdentityTransform<RealType, ImageDimension + 1>;
      typename IdentityIOTransformType::Pointer identityIOTransform = IdentityIOTransformType::New();
      using ConverterType = typename itk::TransformToDisplacementFieldFilter<DisplacementIOFieldType, RealType>;
      typename ConverterType::Pointer idconverter = ConverterType::New();
      idconverter->SetOutputOrigin(outputImage->GetOrigin());
      idconverter->SetOutputStartIndex(outputImage->GetBufferedRegion().GetIndex());
      idconverter->SetSize(outputImage->GetBufferedRegion().GetSize());
      idconverter->SetOutputSpacing(outputImage->GetSpacing());
      idconverter->SetOutputDirection(outputImage->GetDirection());
      idconverter->SetTransform(identityIOTransform);
      idconverter->Update();
      displacementout = idconverter->GetOutput();


      typename ConverterType::Pointer invconverter = ConverterType::New();
      invconverter->SetOutputOrigin(movingInImage->GetOrigin());
      invconverter->SetOutputStartIndex(movingInImage->GetBufferedRegion().GetIndex());
      invconverter->SetSize(movingInImage->GetBufferedRegion().GetSize());
      invconverter->SetOutputSpacing(movingInImage->GetSpacing());
      invconverter->SetOutputDirection(movingInImage->GetDirection());
      invconverter->SetTransform(identityIOTransform);
      invconverter->Update();
      displacementinv = invconverter->GetOutput();
    }


    // Get the number of iterations and use that information to specify the number of levels

    std::vector<unsigned int> iterations =
      parser->ConvertVector<unsigned int>(iterationsOption->GetFunction(currentStage)->GetName());
    unsigned int numberOfLevels = iterations.size();
    if (verbose)
      std::cout << "  number of levels = " << numberOfLevels << std::endl;

    // Get shrink factors

    std::vector<unsigned int> factors =
      parser->ConvertVector<unsigned int>(shrinkFactorsOption->GetFunction(currentStage)->GetName());
    typename AffineRegistrationType::ShrinkFactorsArrayType shrinkFactorsPerLevel;
    shrinkFactorsPerLevel.SetSize(factors.size());

    if (factors.size() != numberOfLevels)
    {
      std::cerr << "ERROR:  The number of shrink factors does not match the number of levels." << std::endl;
      return EXIT_FAILURE;
    }
    else
    {
      for (unsigned int n = 0; n < shrinkFactorsPerLevel.Size(); n++)
      {
        shrinkFactorsPerLevel[n] = factors[n];
      }
      if (verbose)
        std::cout << "  shrink factors per level: " << shrinkFactorsPerLevel << std::endl;
    }

    // Get smoothing sigmas

    std::string smoothingSigmasString = smoothingSigmasOption->GetFunction(currentStage)->GetName();

    bool smoothingSigmasAreInPhysicalUnits = false;

    const size_t mmPosition = smoothingSigmasString.find("mm");
    const size_t voxPosition = smoothingSigmasString.find("vox");

    if (mmPosition != std::string::npos)
    {
      smoothingSigmasString.replace(mmPosition, 2, "");
      smoothingSigmasAreInPhysicalUnits = true;
    }
    else if (voxPosition != std::string::npos)
    {
      smoothingSigmasString.replace(voxPosition, 3, "");
      smoothingSigmasAreInPhysicalUnits = false;
    }
    else
    {
      smoothingSigmasAreInPhysicalUnits = false;
    }

    std::vector<float> sigmas = parser->ConvertVector<float>(smoothingSigmasString);

    typename AffineRegistrationType::SmoothingSigmasArrayType smoothingSigmasPerLevel;
    smoothingSigmasPerLevel.SetSize(sigmas.size());

    if (sigmas.size() != numberOfLevels)
    {
      std::cerr << "ERROR:  The number of smoothing sigmas does not match the number of levels." << std::endl;
      return EXIT_FAILURE;
    }
    else
    {
      for (unsigned int n = 0; n < smoothingSigmasPerLevel.Size(); n++)
      {
        smoothingSigmasPerLevel[n] = sigmas[n];
      }
      if (verbose)
      {
        std::cout << "  smoothing sigmas per level: " << smoothingSigmasPerLevel << std::endl;
        std::cout << "  smoothing sigmas in physical space units: " << smoothingSigmasAreInPhysicalUnits << std::endl;
      }
    }

    // the fixed image is a reference image in 3D while the moving is a 4D image
    // loop over every time point and register image_i+1 to image_i
    //
    // Set up the image metric and scales estimator
    std::vector<unsigned int> timelist;
    std::vector<double>       metriclist;
    for (unsigned int timedim = 0; timedim < timedims; timedim++)
    {
      timelist.push_back(timedim);
    }
    for (unsigned int timedim = 0; timedim < timedims; timedim++)
    {
      typename CompositeTransformType::Pointer compositeTransform = nullptr;
      if (currentStage == static_cast<int>(numberOfStages) - 1)
      {
        compositeTransform = CompositeTransformType::New();
        CompositeTransformVector.push_back(compositeTransform);
      }
      else if (CompositeTransformVector.size() == timedims && !CompositeTransformVector[timedim].IsNull())
      {
        compositeTransform = CompositeTransformVector[timedim];
        if (timedim == 0)
        {
          if (verbose)
            std::cout << " use existing transform " << compositeTransform->GetParameters() << std::endl;
        }
      }
      using IdentityTransformType = itk::IdentityTransform<RealType, ImageDimension>;
      typename IdentityTransformType::Pointer identityTransform = IdentityTransformType::New();
      //
      using ExtractFilterType = itk::ExtractImageFilter<MovingImageType, FixedImageType>;
      typename MovingImageType::RegionType extractRegion = movingImage->GetLargestPossibleRegion();
      extractRegion.SetSize(ImageDimension, 0);
      bool                         maptoneighbor = true;
      typename OptionType::Pointer fixedOption = parser->GetOption("useFixedReferenceImage");
      if (fixedOption && fixedOption->GetNumberOfFunctions())
      {
        std::string fixedFunction = fixedOption->GetFunction(0)->GetName();
        ConvertToLowerCase(fixedFunction);
        if (fixedFunction.compare("1") == 0 || fixedFunction.compare("true") == 0)
        {
          if (timedim == 0)
          {
            if (verbose)
              std::cout << "  using fixed reference image for all frames " << std::endl;
          }
          fixed_time_slice = fixedImage;
          extractRegion.SetIndex(ImageDimension, timedim);
          typename ExtractFilterType::Pointer extractFilter2 = ExtractFilterType::New();
          extractFilter2->SetInput(movingImage);
          extractFilter2->SetDirectionCollapseToSubmatrix();
          if (ImageDimension == 2)
          {
            extractFilter2->SetDirectionCollapseToIdentity();
          }
          extractFilter2->SetExtractionRegion(extractRegion);
          extractFilter2->Update();
          moving_time_slice = extractFilter2->GetOutput();
          maptoneighbor = false;
        }
      }

      if (maptoneighbor)
      {
        extractRegion.SetIndex(ImageDimension, timedim);
        typename ExtractFilterType::Pointer extractFilter = ExtractFilterType::New();
        extractFilter->SetInput(movingImage);
        extractFilter->SetDirectionCollapseToSubmatrix();
        if (ImageDimension == 2)
        {
          extractFilter->SetDirectionCollapseToIdentity();
        }
        extractFilter->SetExtractionRegion(extractRegion);
        extractFilter->Update();
        fixed_time_slice = extractFilter->GetOutput();
        unsigned int td = timedim + 1;
        if (td > timedims - 1)
        {
          td = timedims - 1;
        }
        extractRegion.SetIndex(ImageDimension, td);
        typename ExtractFilterType::Pointer extractFilter2 = ExtractFilterType::New();
        extractFilter2->SetInput(movingImage);
        extractFilter2->SetDirectionCollapseToSubmatrix();
        if (ImageDimension == 2)
        {
          extractFilter->SetDirectionCollapseToIdentity();
        }
        extractFilter2->SetExtractionRegion(extractRegion);
        extractFilter2->Update();
        moving_time_slice = extractFilter2->GetOutput();
      }

      typename FixedImageType::Pointer preprocessFixedImage =
        PreprocessImage<FixedImageType>(fixed_time_slice, 0, 1, 0.001, 0.999, nullptr);

      if (verbose)
        std::cout << "  use histogram matching " << doHistogramMatch << std::endl;

      typename FixedImageType::Pointer preprocessMovingImage =
        PreprocessImage<FixedImageType>(moving_time_slice, 0, 1, 0.001, 0.999, preprocessFixedImage);

      using MetricType = itk::ImageToImageMetricv4<FixedImageType, FixedImageType>;
      typename MetricType::Pointer metric;

      std::string whichMetric = metricOption->GetFunction(currentStage)->GetName();
      ConvertToLowerCase(whichMetric);

      float samplingPercentage = 1.0;
      if (metricOption->GetFunction(0)->GetNumberOfParameters() > 5)
      {
        samplingPercentage = parser->Convert<float>(metricOption->GetFunction(currentStage)->GetParameter(5));
      }

      std::string samplingStrategy = "";
      if (metricOption->GetFunction(0)->GetNumberOfParameters() > 4)
      {
        samplingStrategy = metricOption->GetFunction(currentStage)->GetParameter(4);
      }
      ConvertToLowerCase(samplingStrategy);
      typename AffineRegistrationType::MetricSamplingStrategyEnum metricSamplingStrategy =
        AffineRegistrationType::MetricSamplingStrategyEnum::NONE;
      if (std::strcmp(samplingStrategy.c_str(), "random") == 0)
      {
        if (timedim == 0)
        {
          if (verbose)
            std::cout << "  random sampling (percentage = " << samplingPercentage << ")" << std::endl;
        }
        metricSamplingStrategy = AffineRegistrationType::MetricSamplingStrategyEnum::RANDOM;
      }
      if (std::strcmp(samplingStrategy.c_str(), "regular") == 0)
      {
        if (timedim == 0)
        {
          if (verbose)
            std::cout << "  regular sampling (percentage = " << samplingPercentage << ")" << std::endl;
        }
        metricSamplingStrategy = AffineRegistrationType::MetricSamplingStrategyEnum::REGULAR;
      }

      bool useGradientFilter = false;
      if (metricOption->GetFunction(0)->GetNumberOfParameters() > 6)
      {
        useGradientFilter = parser->Convert<bool>(metricOption->GetFunction(currentStage)->GetParameter(6));
      }

      if (std::strcmp(whichMetric.c_str(), "cc") == 0)
      {
        auto radiusOption = parser->Convert<unsigned int>(metricOption->GetFunction(currentStage)->GetParameter(3));

        if (timedim == 0)
        {
          if (verbose)
            std::cout << "  using the CC metric (radius = " << radiusOption << ")." << std::endl;
        }
        using CorrelationMetricType =
          itk::ANTSNeighborhoodCorrelationImageToImageMetricv4<FixedImageType, FixedImageType>;
        typename CorrelationMetricType::Pointer    correlationMetric = CorrelationMetricType::New();
        typename CorrelationMetricType::RadiusType radius;
        radius.Fill(radiusOption);
        correlationMetric->SetRadius(radius);
        correlationMetric->SetUseMovingImageGradientFilter(useGradientFilter);
        correlationMetric->SetUseFixedImageGradientFilter(useGradientFilter);

        metric = correlationMetric;
      }
      else if (std::strcmp(whichMetric.c_str(), "mi") == 0)
      {
        auto binOption = parser->Convert<unsigned int>(metricOption->GetFunction(currentStage)->GetParameter(3));

        if (timedim == 0)
        {
          if (verbose)
            std::cout << "  using the Mattes MI metric." << std::endl;
        }
        using MutualInformationMetricType =
          itk::MattesMutualInformationImageToImageMetricv4<FixedImageType, FixedImageType>;
        typename MutualInformationMetricType::Pointer mutualInformationMetric = MutualInformationMetricType::New();
        // mutualInformationMetric = mutualInformationMetric;
        mutualInformationMetric->SetNumberOfHistogramBins(binOption);
        mutualInformationMetric->SetUseMovingImageGradientFilter(useGradientFilter);
        mutualInformationMetric->SetUseFixedImageGradientFilter(useGradientFilter);
        metric = mutualInformationMetric;
      }
      else if (std::strcmp(whichMetric.c_str(), "demons") == 0)
      {
        if (timedim == 0)
        {
          if (verbose)
            std::cout << "  using the Demons metric." << std::endl;
        }
        using DemonsMetricType = itk::MeanSquaresImageToImageMetricv4<FixedImageType, FixedImageType>;
        typename DemonsMetricType::Pointer demonsMetric = DemonsMetricType::New();
        demonsMetric->SetUseMovingImageGradientFilter(useGradientFilter);
        demonsMetric->SetUseFixedImageGradientFilter(useGradientFilter);
        // demonsMetric = demonsMetric;
        metric = demonsMetric;
      }
      else if (std::strcmp(whichMetric.c_str(), "gc") == 0)
      {
        if (timedim == 0)
        {
          if (verbose)
            std::cout << "  using the global correlation metric." << std::endl;
        }
        using corrMetricType = itk::CorrelationImageToImageMetricv4<FixedImageType, FixedImageType>;
        typename corrMetricType::Pointer corrMetric = corrMetricType::New();
        corrMetric->SetUseMovingImageGradientFilter(useGradientFilter);
        corrMetric->SetUseFixedImageGradientFilter(useGradientFilter);
        metric = corrMetric;
        if (verbose)
          std::cout << "  global corr metric set " << std::endl;
      }
      else
      {
        std::cerr << "ERROR: Unrecognized image metric: " << whichMetric << std::endl;
        return EXIT_FAILURE;
      }
      metric->SetVirtualDomainFromImage(fixed_time_slice);

      using ScalesEstimatorType = itk::RegistrationParameterScalesFromPhysicalShift<MetricType>;
      typename ScalesEstimatorType::Pointer scalesEstimator = ScalesEstimatorType::New();
      scalesEstimator->SetMetric(metric);
      scalesEstimator->SetTransformForward(true);

      auto learningRate = parser->Convert<float>(transformOption->GetFunction(currentStage)->GetParameter(0));

      using OptimizerType = itk::ConjugateGradientLineSearchOptimizerv4;
      OptimizerType::Pointer optimizer = OptimizerType::New();
      optimizer->SetNumberOfIterations(iterations[0]);
      optimizer->SetMinimumConvergenceValue(1.e-7);
      optimizer->SetConvergenceWindowSize(10);
      optimizer->SetLowerLimit(0);
      optimizer->SetUpperLimit(2);
      optimizer->SetEpsilon(0.1);

      typename OptionType::Pointer scalesOption = parser->GetOption("useScalesEstimator");
      if (scalesOption && scalesOption->GetNumberOfFunctions())
      {
        std::string scalesFunction = scalesOption->GetFunction(0)->GetName();
        ConvertToLowerCase(scalesFunction);
        if (scalesFunction.compare("1") == 0 || scalesFunction.compare("true") == 0)
        {
          if (timedim == 0)
          {
            if (verbose)
              std::cout << "  employing scales estimator " << std::endl;
          }
          optimizer->SetScalesEstimator(scalesEstimator);
        }
        else
        {
          if (timedim == 0)
          {
            if (verbose)
              std::cout << "  not employing scales estimator " << scalesFunction << std::endl;
          }
        }
      }
      optimizer->SetMaximumStepSizeInPhysicalUnits(learningRate);
      optimizer->SetDoEstimateLearningRateOnce(doEstimateLearningRateOnce);
      optimizer->SetDoEstimateLearningRateAtEachIteration(!doEstimateLearningRateOnce);
      //    optimizer->SetMaximumNewtonStepSizeInPhysicalUnits(sqrt(small_step)*learningR);

      // Set up the image registration methods along with the transforms
      std::string whichTransform = transformOption->GetFunction(currentStage)->GetName();
      ConvertToLowerCase(whichTransform);

      // initialize with moments
      using ImageCalculatorType = typename itk::ImageMomentsCalculator<FixedImageType>;
      typename ImageCalculatorType::Pointer calculator1 = ImageCalculatorType::New();
      typename ImageCalculatorType::Pointer calculator2 = ImageCalculatorType::New();
      calculator1->SetImage(fixed_time_slice);
      calculator2->SetImage(moving_time_slice);
      typename ImageCalculatorType::VectorType fixed_center;
      fixed_center.Fill(0);
      typename ImageCalculatorType::VectorType moving_center;
      moving_center.Fill(0);
      try
      {
        calculator1->Compute();
        fixed_center = calculator1->GetCenterOfGravity();
        try
        {
          calculator2->Compute();
          moving_center = calculator2->GetCenterOfGravity();
        }
        catch (...)
        {
          fixed_center.Fill(0);
        }
      }
      catch (...)
      {
        // Rcpp::Rcerr << " zero image1 error ";
      }
      typename AffineTransformType::OffsetType trans;
      itk::Point<RealType, ImageDimension>     trans2;
      for (unsigned int i = 0; i < ImageDimension; i++)
      {
        trans[i] = moving_center[i] - fixed_center[i];
        trans2[i] = fixed_center[i];
      }
      if (std::strcmp(whichTransform.c_str(), "affine") == 0)
      {
        typename AffineRegistrationType::Pointer affineRegistration = AffineRegistrationType::New();
        if (antsRandomSeed != 0)
        {
          affineRegistration->MetricSamplingReinitializeSeed(antsRandomSeed);
        }
        typename AffineTransformType::Pointer affineTransform = AffineTransformType::New();
        affineTransform->SetIdentity();
        affineTransform->SetOffset(trans);
        affineTransform->SetCenter(trans2);
        nparams = affineTransform->GetNumberOfParameters() + 2;
        metric->SetFixedImage(preprocessFixedImage);
        metric->SetVirtualDomainFromImage(preprocessFixedImage);
        metric->SetMovingImage(preprocessMovingImage);
        metric->SetMovingTransform(affineTransform);
        typename ScalesEstimatorType::ScalesType scales(affineTransform->GetNumberOfParameters());
        typename MetricType::ParametersType      newparams(affineTransform->GetParameters());
        metric->SetParameters(newparams);
        metric->Initialize();
        scalesEstimator->SetMetric(metric);
        scalesEstimator->EstimateScales(scales);
        optimizer->SetScales(scales);
        if (compositeTransform->GetNumberOfTransforms() > 0)
        {
          affineRegistration->SetMovingInitialTransform(compositeTransform);
        }
        affineRegistration->SetFixedImage(preprocessFixedImage);
        affineRegistration->SetMovingImage(preprocessMovingImage);
        affineRegistration->SetNumberOfLevels(numberOfLevels);
        affineRegistration->SetShrinkFactorsPerLevel(shrinkFactorsPerLevel);
        affineRegistration->SetSmoothingSigmasPerLevel(smoothingSigmasPerLevel);
        affineRegistration->SetSmoothingSigmasAreSpecifiedInPhysicalUnits(smoothingSigmasAreInPhysicalUnits);
        affineRegistration->SetMetricSamplingStrategy(metricSamplingStrategy);
        affineRegistration->SetMetricSamplingPercentage(samplingPercentage);
        affineRegistration->SetMetric(metric);
        affineRegistration->SetOptimizer(optimizer);

        using AffineCommandType = CommandIterationUpdate<AffineRegistrationType>;
        typename AffineCommandType::Pointer affineObserver = AffineCommandType::New();
        affineObserver->SetNumberOfIterations(iterations);

        affineRegistration->AddObserver(itk::IterationEvent(), affineObserver);

        try
        {
          if (verbose)
            std::cout << std::endl << "*** Running affine registration ***" << timedim << std::endl << std::endl;
          affineRegistration->Update();
        }
        catch (const itk::ExceptionObject & e)
        {
          std::cerr << "Exception caught: " << e << std::endl;
          return EXIT_FAILURE;
        }
        compositeTransform->AddTransform(affineRegistration->GetModifiableTransform());
        // Write out the affine transform
        std::string filename = outputPrefix + std::string("TimeSlice") + ants_moco_to_string<unsigned int>(timedim) +
                               std::string("Affine.txt");
        using TransformWriterType = itk::TransformFileWriter;
        typename TransformWriterType::Pointer transformWriter = TransformWriterType::New();
        transformWriter->SetInput(affineRegistration->GetOutput()->Get());
        transformWriter->SetFileName(filename.c_str());
#if ITK_VERSION_MAJOR >= 5
        transformWriter->SetUseCompression(true);
#endif
        //      transformWriter->Update();
        if (timedim == 0)
        {
          param_values.set_size(timedims, nparams);
          param_values.fill(0);
        }
        for (unsigned int i = 0; i < nparams - 2; i++)
        {
          param_values(timedim, i + 2) = affineRegistration->GetOutput()->Get()->GetParameters()[i];
        }
      }
      else if (std::strcmp(whichTransform.c_str(), "rigid") == 0)
      {
        using RigidTransformType = typename RigidTransformTraits<ImageDimension>::TransformType;
        typename RigidTransformType::Pointer rigidTransform = RigidTransformType::New();
        rigidTransform->SetOffset(trans);
        rigidTransform->SetCenter(trans2);
        nparams = rigidTransform->GetNumberOfParameters() + 2;
        using RigidRegistrationType =
          itk::ImageRegistrationMethodv4<FixedImageType, FixedImageType, RigidTransformType>;
        typename RigidRegistrationType::Pointer rigidRegistration = RigidRegistrationType::New();
        if (antsRandomSeed != 0)
        {
          rigidRegistration->MetricSamplingReinitializeSeed(antsRandomSeed);
        }
        metric->SetFixedImage(preprocessFixedImage);
        metric->SetVirtualDomainFromImage(preprocessFixedImage);
        metric->SetMovingImage(preprocessMovingImage);
        metric->SetMovingTransform(rigidTransform);
        typename ScalesEstimatorType::ScalesType scales(rigidTransform->GetNumberOfParameters());
        typename MetricType::ParametersType      newparams(rigidTransform->GetParameters());
        metric->SetParameters(newparams);
        metric->Initialize();
        scalesEstimator->SetMetric(metric);
        scalesEstimator->EstimateScales(scales);
        optimizer->SetScales(scales);
        rigidRegistration->SetFixedImage(preprocessFixedImage);
        rigidRegistration->SetMovingImage(preprocessMovingImage);
        rigidRegistration->SetNumberOfLevels(numberOfLevels);
        rigidRegistration->SetShrinkFactorsPerLevel(shrinkFactorsPerLevel);
        rigidRegistration->SetSmoothingSigmasPerLevel(smoothingSigmasPerLevel);
        rigidRegistration->SetSmoothingSigmasAreSpecifiedInPhysicalUnits(smoothingSigmasAreInPhysicalUnits);
        rigidRegistration->SetMetric(metric);
        rigidRegistration->SetMetricSamplingStrategy(
          static_cast<typename RigidRegistrationType::MetricSamplingStrategyEnum>(metricSamplingStrategy));
        rigidRegistration->SetMetricSamplingPercentage(samplingPercentage);
        rigidRegistration->SetOptimizer(optimizer);
        if (compositeTransform->GetNumberOfTransforms() > 0)
        {
          rigidRegistration->SetMovingInitialTransform(compositeTransform);
        }

        using RigidCommandType = CommandIterationUpdate<RigidRegistrationType>;
        typename RigidCommandType::Pointer rigidObserver = RigidCommandType::New();
        rigidObserver->SetNumberOfIterations(iterations);
        rigidRegistration->AddObserver(itk::IterationEvent(), rigidObserver);
        try
        {
          if (verbose)
            std::cout << std::endl << "*** Running rigid registration ***" << timedim << std::endl << std::endl;
          rigidRegistration->Update();
        }
        catch (const itk::ExceptionObject & e)
        {
          std::cerr << "Exception caught: " << e << std::endl;
          return EXIT_FAILURE;
        }
        compositeTransform->AddTransform(rigidRegistration->GetModifiableTransform());
        // Write out the rigid transform
        std::string filename = outputPrefix + std::string("TimeSlice") + ants_moco_to_string<unsigned int>(timedim) +
                               std::string("Rigid.txt");
        using TransformWriterType = itk::TransformFileWriter;
        typename TransformWriterType::Pointer transformWriter = TransformWriterType::New();
        transformWriter->SetInput(rigidRegistration->GetOutput()->Get());
        transformWriter->SetFileName(filename.c_str());
#if ITK_VERSION_MAJOR >= 5
        transformWriter->SetUseCompression(true);
#endif
        //      transformWriter->Update();
        if (timedim == 0)
        {
          param_values.set_size(timedims, nparams);
          param_values.fill(0);
        }
        for (unsigned int i = 0; i < nparams - 2; i++)
        {
          param_values(timedim, i + 2) = rigidRegistration->GetOutput()->Get()->GetParameters()[i];
        }
      }
      else if (std::strcmp(whichTransform.c_str(), "gaussiandisplacementfield") == 0 ||
               std::strcmp(whichTransform.c_str(), "gdf") == 0)
      {
        RealType sigmaForUpdateField =
          parser->Convert<float>(transformOption->GetFunction(currentStage)->GetParameter(1));
        RealType sigmaForTotalField =
          parser->Convert<float>(transformOption->GetFunction(currentStage)->GetParameter(2));
        const unsigned int VImageDimension = ImageDimension;
        VectorType         zeroVector(0.0);
        // ORIENTATION ALERT: Original code set image size to
        // fixedImage buffered region, & if fixedImage BufferedRegion
        // != LargestPossibleRegion, this code would be wrong.
        typename DisplacementFieldType::Pointer displacementField =
          AllocImage<DisplacementFieldType>(preprocessFixedImage, zeroVector);
        using GaussianDisplacementFieldTransformType =
          itk::GaussianSmoothingOnUpdateDisplacementFieldTransform<RealType, VImageDimension>;

        using DisplacementFieldRegistrationType =
          itk::ImageRegistrationMethodv4<FixedImageType, FixedImageType, GaussianDisplacementFieldTransformType>;
        typename DisplacementFieldRegistrationType::Pointer displacementFieldRegistration =
          DisplacementFieldRegistrationType::New();

        typename GaussianDisplacementFieldTransformType::Pointer outputDisplacementFieldTransform =
          displacementFieldRegistration->GetModifiableTransform();

        // Create the transform adaptors

        using DisplacementFieldTransformAdaptorType =
          itk::GaussianSmoothingOnUpdateDisplacementFieldTransformParametersAdaptor<
            GaussianDisplacementFieldTransformType>;
        typename DisplacementFieldRegistrationType::TransformParametersAdaptorsContainerType adaptors;

        // Extract parameters
        outputDisplacementFieldTransform->SetGaussianSmoothingVarianceForTheUpdateField(sigmaForUpdateField);
        outputDisplacementFieldTransform->SetGaussianSmoothingVarianceForTheTotalField(sigmaForTotalField);
        outputDisplacementFieldTransform->SetDisplacementField(displacementField);
        for (unsigned int level = 0; level < numberOfLevels; level++)
        {
          using ShrinkFilterType = itk::ShrinkImageFilter<DisplacementFieldType, DisplacementFieldType>;
          typename ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New();
          shrinkFilter->SetShrinkFactors(shrinkFactorsPerLevel[level]);
          shrinkFilter->SetInput(displacementField);
          shrinkFilter->Update();
          typename DisplacementFieldTransformAdaptorType::Pointer fieldTransformAdaptor =
            DisplacementFieldTransformAdaptorType::New();
          fieldTransformAdaptor->SetRequiredSpacing(shrinkFilter->GetOutput()->GetSpacing());
          fieldTransformAdaptor->SetRequiredSize(shrinkFilter->GetOutput()->GetBufferedRegion().GetSize());
          fieldTransformAdaptor->SetRequiredDirection(shrinkFilter->GetOutput()->GetDirection());
          fieldTransformAdaptor->SetRequiredOrigin(shrinkFilter->GetOutput()->GetOrigin());
          fieldTransformAdaptor->SetTransform(outputDisplacementFieldTransform);
          adaptors.push_back(fieldTransformAdaptor.GetPointer());
        }
        displacementFieldRegistration->SetFixedImage(0, preprocessFixedImage);
        displacementFieldRegistration->SetMovingImage(0, preprocessMovingImage);
        displacementFieldRegistration->SetMetric(metric);
        displacementFieldRegistration->SetNumberOfLevels(numberOfLevels);
        displacementFieldRegistration->SetShrinkFactorsPerLevel(shrinkFactorsPerLevel);
        displacementFieldRegistration->SetSmoothingSigmasPerLevel(smoothingSigmasPerLevel);
        displacementFieldRegistration->SetSmoothingSigmasAreSpecifiedInPhysicalUnits(smoothingSigmasAreInPhysicalUnits);
        displacementFieldRegistration->SetMetricSamplingStrategy(
          static_cast<typename DisplacementFieldRegistrationType::MetricSamplingStrategyEnum>(metricSamplingStrategy));
        displacementFieldRegistration->SetMetricSamplingPercentage(samplingPercentage);
        displacementFieldRegistration->SetOptimizer(optimizer);
        displacementFieldRegistration->SetTransformParametersAdaptorsPerLevel(adaptors);
        if (compositeTransform->GetNumberOfTransforms() > 0)
        {
          displacementFieldRegistration->SetMovingInitialTransform(compositeTransform);
        }
        try
        {
          displacementFieldRegistration->Update();
        }
        catch (const itk::ExceptionObject & e)
        {
          std::cerr << "Exception caught: " << e << std::endl;
          return EXIT_FAILURE;
        }
        compositeTransform->AddTransform(outputDisplacementFieldTransform);
        if (timedim == 0)
        {
          param_values.set_size(timedims, nparams);
          param_values.fill(0);
        }
      }
      else if (std::strcmp(whichTransform.c_str(), "SyN") == 0 || std::strcmp(whichTransform.c_str(), "syn") == 0)
      {
        RealType sigmaForUpdateField =
          parser->Convert<float>(transformOption->GetFunction(currentStage)->GetParameter(1));
        RealType sigmaForTotalField =
          parser->Convert<float>(transformOption->GetFunction(currentStage)->GetParameter(2));
        const unsigned int VImageDimension = ImageDimension;
        VectorType         zeroVector(0.0);

        typename DisplacementFieldType::Pointer displacementField =
          AllocImage<DisplacementFieldType>(preprocessFixedImage, zeroVector);

        typename DisplacementFieldType::Pointer inverseDisplacementField =
          AllocImage<DisplacementFieldType>(preprocessFixedImage, zeroVector);

        using DisplacementFieldTransformType = itk::DisplacementFieldTransform<RealType, VImageDimension>;
        using DisplacementFieldRegistrationType =
          itk::SyNImageRegistrationMethod<FixedImageType, FixedImageType, DisplacementFieldTransformType>;
        typename DisplacementFieldRegistrationType::Pointer displacementFieldRegistration =
          DisplacementFieldRegistrationType::New();

        typename DisplacementFieldTransformType::Pointer outputDisplacementFieldTransform =
          displacementFieldRegistration->GetModifiableTransform();

        // Create the transform adaptors

        using DisplacementFieldTransformAdaptorType =
          itk::DisplacementFieldTransformParametersAdaptor<DisplacementFieldTransformType>;
        typename DisplacementFieldRegistrationType::TransformParametersAdaptorsContainerType adaptors;
        // Create the transform adaptors
        // For the gaussian displacement field, the specified variances are in image spacing terms
        // and, in normal practice, we typically don't change these values at each level.  However,
        // if the user wishes to add that option, they can use the class
        // GaussianSmoothingOnUpdateDisplacementFieldTransformAdaptor
        for (unsigned int level = 0; level < numberOfLevels; level++)
        {
          // TODO:
          // We use the shrink image filter to calculate the fixed parameters of the virtual
          // domain at each level.  To speed up calculation and avoid unnecessary memory
          // usage, we could calculate these fixed parameters directly.
          using ShrinkFilterType = itk::ShrinkImageFilter<DisplacementFieldType, DisplacementFieldType>;
          typename ShrinkFilterType::Pointer shrinkFilter = ShrinkFilterType::New();
          shrinkFilter->SetShrinkFactors(shrinkFactorsPerLevel[level]);
          shrinkFilter->SetInput(displacementField);
          shrinkFilter->Update();

          typename DisplacementFieldTransformAdaptorType::Pointer fieldTransformAdaptor =
            DisplacementFieldTransformAdaptorType::New();
          fieldTransformAdaptor->SetRequiredSpacing(shrinkFilter->GetOutput()->GetSpacing());
          fieldTransformAdaptor->SetRequiredSize(shrinkFilter->GetOutput()->GetBufferedRegion().GetSize());
          fieldTransformAdaptor->SetRequiredDirection(shrinkFilter->GetOutput()->GetDirection());
          fieldTransformAdaptor->SetRequiredOrigin(shrinkFilter->GetOutput()->GetOrigin());
          fieldTransformAdaptor->SetTransform(outputDisplacementFieldTransform);

          adaptors.push_back(fieldTransformAdaptor.GetPointer());
        }

        // Extract parameters
        typename DisplacementFieldRegistrationType::NumberOfIterationsArrayType numberOfIterationsPerLevel;
        numberOfIterationsPerLevel.SetSize(numberOfLevels);
        if (timedim == 0)
        {
          if (verbose)
            std::cout << "SyN iterations:";
        }
        for (unsigned int d = 0; d < numberOfLevels; d++)
        {
          numberOfIterationsPerLevel[d] = iterations[d]; // currentStageIterations[d];
          if (timedim == 0)
          {
            if (verbose)
              std::cout << numberOfIterationsPerLevel[d] << " ";
          }
        }
        if (timedim == 0)
        {
          if (verbose)
            std::cout << std::endl;
        }

        const RealType varianceForUpdateField = sigmaForUpdateField;
        const RealType varianceForTotalField = sigmaForTotalField;
        displacementFieldRegistration->SetFixedImage(0, preprocessFixedImage);
        displacementFieldRegistration->SetMovingImage(0, preprocessMovingImage);
        displacementFieldRegistration->SetMetric(metric);

        if (compositeTransform->GetNumberOfTransforms() > 0)
        {
          displacementFieldRegistration->SetMovingInitialTransform(compositeTransform);
        }
        displacementFieldRegistration->SetDownsampleImagesForMetricDerivatives(true);
        displacementFieldRegistration->SetAverageMidPointGradients(false);
        displacementFieldRegistration->SetNumberOfLevels(numberOfLevels);
        displacementFieldRegistration->SetShrinkFactorsPerLevel(shrinkFactorsPerLevel);
        displacementFieldRegistration->SetSmoothingSigmasPerLevel(smoothingSigmasPerLevel);
        displacementFieldRegistration->SetSmoothingSigmasAreSpecifiedInPhysicalUnits(smoothingSigmasAreInPhysicalUnits);
        displacementFieldRegistration->SetLearningRate(learningRate);
        displacementFieldRegistration->SetConvergenceThreshold(1.e-8);
        displacementFieldRegistration->SetConvergenceWindowSize(10);
        displacementFieldRegistration->SetNumberOfIterationsPerLevel(numberOfIterationsPerLevel);
        displacementFieldRegistration->SetTransformParametersAdaptorsPerLevel(adaptors);
        displacementFieldRegistration->SetGaussianSmoothingVarianceForTheUpdateField(varianceForUpdateField);
        displacementFieldRegistration->SetGaussianSmoothingVarianceForTheTotalField(varianceForTotalField);
        outputDisplacementFieldTransform->SetDisplacementField(displacementField);
        outputDisplacementFieldTransform->SetInverseDisplacementField(inverseDisplacementField);
        try
        {
          displacementFieldRegistration->Update();
        }
        catch (const itk::ExceptionObject & e)
        {
          std::cerr << "Exception caught: " << e << std::endl;
          return EXIT_FAILURE;
        }
        // Add calculated transform to the composite transform
        compositeTransform->AddTransform(outputDisplacementFieldTransform);
        if (timedim == 0)
        {
          param_values.set_size(timedims, nparams);
          param_values.fill(0);
        }
      }
      else
      {
        std::cerr << "ERROR:  Unrecognized transform option - " << whichTransform << std::endl;
        return EXIT_FAILURE;
      }
      if (currentStage == static_cast<int>(numberOfStages) - 1)
      {
        param_values(timedim, 1) = metric->GetValue();
      }
      metriclist.push_back(param_values(timedim, 1));
      metricmean += param_values(timedim, 1) / (double)timedims;
      // resample the moving image and then put it in its place
      using ResampleFilterType = itk::ResampleImageFilter<FixedImageType, FixedImageType>;
      typename ResampleFilterType::Pointer resampler = ResampleFilterType::New();
      resampler->SetTransform(compositeTransform);
      resampler->SetInput(moving_time_slice);
      resampler->SetOutputParametersFromImage(fixed_time_slice);
      resampler->SetDefaultPixelValue(0);
      resampler->SetInterpolator(interpolator);
      resampler->Update();
      if (verbose)
        std::cout << " done resampling timepoint : " << timedim << std::endl;

      /** Here, we put the resampled 3D image into the 4D volume */
      using Iterator = itk::ImageRegionIteratorWithIndex<FixedImageType>;
      Iterator vfIter2(resampler->GetOutput(), resampler->GetOutput()->GetLargestPossibleRegion());
      for (vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2)
      {
        typename FixedImageType::PixelType  fval = vfIter2.Get();
        typename MovingImageType::IndexType ind;
        for (unsigned int xx = 0; xx < ImageDimension; xx++)
        {
          ind[xx] = vfIter2.GetIndex()[xx];
        }
        unsigned int tdim = timedim;
        if (tdim > (timedims - 1))
        {
          tdim = timedims - 1;
        }
        ind[ImageDimension] = tdim;
        outputImage->SetPixel(ind, fval);
      }
      if (writeDisplacementField > 0)
      {
        using ConverterType = typename itk::TransformToDisplacementFieldFilter<DisplacementFieldType, RealType>;
        typename ConverterType::Pointer converter = ConverterType::New();
        converter->SetOutputOrigin(fixed_time_slice->GetOrigin());
        converter->SetOutputStartIndex(fixed_time_slice->GetBufferedRegion().GetIndex());
        converter->SetSize(fixed_time_slice->GetBufferedRegion().GetSize());
        converter->SetOutputSpacing(fixed_time_slice->GetSpacing());
        converter->SetOutputDirection(fixed_time_slice->GetDirection());
        converter->SetTransform(compositeTransform);
        converter->Update();
        /** Here, we put the 3d tx into a 4d displacement field */
        for (vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2)
        {
          VectorType   vec = converter->GetOutput()->GetPixel(vfIter2.GetIndex());
          VectorIOType vecout;
          vecout.Fill(0);
          typename MovingIOImageType::IndexType ind;
          for (unsigned int xx = 0; xx < ImageDimension; xx++)
          {
            ind[xx] = vfIter2.GetIndex()[xx];
            vecout[xx] = vec[xx];
          }
          unsigned int tdim = timedim;
          if (tdim > (timedims - 1))
          {
            tdim = timedims - 1;
          }
          ind[ImageDimension] = tdim;
          displacementout->SetPixel(ind, vecout);
        }
#
        typename ConverterType::Pointer converter2 = ConverterType::New();
        converter2->SetOutputOrigin(moving_time_slice->GetOrigin());
        converter2->SetOutputStartIndex(moving_time_slice->GetBufferedRegion().GetIndex());
        converter2->SetSize(moving_time_slice->GetBufferedRegion().GetSize());
        converter2->SetOutputSpacing(moving_time_slice->GetSpacing());
        converter2->SetOutputDirection(moving_time_slice->GetDirection());
        converter2->SetTransform(compositeTransform->GetInverseTransform());
        converter2->Update();
        /** Here, we put the 3d tx into a 4d displacement field */
        Iterator vfIterInv(moving_time_slice, moving_time_slice->GetLargestPossibleRegion());
        for (vfIterInv.GoToBegin(); !vfIterInv.IsAtEnd(); ++vfIterInv)
        {
          VectorType   vec = converter2->GetOutput()->GetPixel(vfIterInv.GetIndex());
          VectorIOType vecout;
          vecout.Fill(0);
          typename MovingIOImageType::IndexType ind;
          for (unsigned int xx = 0; xx < ImageDimension; xx++)
          {
            ind[xx] = vfIterInv.GetIndex()[xx];
            vecout[xx] = vec[xx];
          }
          unsigned int tdim = timedim;
          if (tdim > (timedims - 1))
          {
            tdim = timedims - 1;
          }
          ind[ImageDimension] = tdim;
          displacementinv->SetPixel(ind, vecout);
        }
      }
    }
    if (outputOption && outputOption->GetFunction(0)->GetNumberOfParameters() > 1 && currentStage == 0)
    {
      std::string fileName = outputOption->GetFunction(0)->GetParameter(1);
      if (outputPrefix.length() < 3)
      {
        outputPrefix = outputOption->GetFunction(0)->GetName();
      }
      if (verbose)
        std::cout << "motion corrected out " << fileName << std::endl;
      ANTs::WriteImage<MovingIOImageType>(outputImage, fileName.c_str());
    }
    if (outputOption && outputOption->GetFunction(0)->GetNumberOfParameters() > 2 && outputImage && currentStage == 0)
    {
      std::string                        fileName = outputOption->GetFunction(0)->GetParameter(2);
      typename FixedIOImageType::Pointer avgImage;
      using ExtractFilterType = itk::ExtractImageFilter<MovingImageType, FixedIOImageType>;
      typename MovingImageType::RegionType extractRegion = movingImage->GetLargestPossibleRegion();
      extractRegion.SetSize(ImageDimension, 0);
      typename ExtractFilterType::Pointer extractFilter = ExtractFilterType::New();
      extractFilter->SetInput(movingImage);
      extractFilter->SetDirectionCollapseToSubmatrix();
      if (ImageDimension == 2)
      {
        extractFilter->SetDirectionCollapseToIdentity();
      }
      unsigned int td = 0;
      extractRegion.SetIndex(ImageDimension, td);
      extractFilter->SetExtractionRegion(extractRegion);
      extractFilter->Update();
      avgImage = extractFilter->GetOutput();
      std::sort(timelist.begin(), timelist.end(), ants_moco_index_cmp<std::vector<double> &>(metriclist));
      if (nimagestoavg == 0)
      {
        nimagestoavg = timelist.size();
      }
      std::vector<unsigned int> timelistsort;
      for (unsigned int i = 0; i < nimagestoavg; i++)
      {
        if (i < timelist.size())
        {
          timelistsort.push_back(timelist[i]);
        }
        if (verbose)
          std::cout << " i^th value " << i << "  is " << metriclist[timelist[i]] << std::endl;
      }
      AverageTimeImages<MovingIOImageType, FixedIOImageType>(outputImage, fixed_time_slice, timelistsort);
      if (verbose)
        std::cout << " write average post " << fileName << std::endl;
      ANTs::WriteImage<FixedIOImageType>(fixed_time_slice, fileName.c_str());
    }
  }
  if (writeDisplacementField > 0)
  {
    std::string dfn = outputPrefix + std::string("Warp.nii.gz");
    ANTs::WriteImage<DisplacementIOFieldType>(displacementout, dfn.c_str());
    dfn = outputPrefix + std::string("InverseWarp.nii.gz");
    ANTs::WriteImage<DisplacementIOFieldType>(displacementinv, dfn.c_str());
  }

  totalTimer.Stop();
  if (verbose)
    std::cout << std::endl
              << "Total elapsed time: " << totalTimer.GetMean() << " averagemetric " << metricmean << std::endl;
  {
    std::vector<std::string> ColumnHeaders;
    std::string              colname;
    colname = std::string("MetricPre");
    ColumnHeaders.push_back(colname);
    colname = std::string("MetricPost");
    ColumnHeaders.push_back(colname);
    for (unsigned int nv = 2; nv < nparams; nv++)
    {
      std::string _colname = std::string("MOCOparam") + ants_moco_to_string<unsigned int>(nv - 2);
      ColumnHeaders.push_back(_colname);
    }
    using WriterType = itk::CSVNumericObjectFileWriter<double, 1, 1>;
    WriterType::Pointer writer = WriterType::New();
    std::string         fnmp;
    if (verbose)
      std::cout << " get motion corr params " << outputPrefix << std::endl;
    if (outputPrefix[0] == '0' && outputPrefix[1] == 'x')
    {
      void * ptr;
      std::sscanf(outputPrefix.c_str(), "%p", (void **)&ptr);
      //      std::stringstream strstream;
      //      strstream << outputPrefix;
      //      void* ptr;
      //      strstream >> ptr;
      (static_cast<std::pair<std::vector<std::string>, vnl_matrix<float>> *>(ptr))->first = ColumnHeaders;
      (static_cast<std::pair<std::vector<std::string>, vnl_matrix<double>> *>(ptr))->second = param_values;
      if (verbose)
        std::cout << "motion-correction params written" << std::endl;
    }
    else
    {
      fnmp = outputPrefix + std::string("MOCOparams.csv");
      if (verbose)
        std::cout << " write " << fnmp << std::endl;
      writer->SetFileName(fnmp.c_str());
      writer->SetColumnHeaders(ColumnHeaders);
      writer->SetInput(&param_values);
      writer->Write();
    }
  }

  return EXIT_SUCCESS;
}

void
antsMotionCorrInitializeCommandLineOptions(itk::ants::CommandLineParser * parser)
{
  using OptionType = itk::ants::CommandLineParser::OptionType;

  {
    std::string description = std::string("This option forces the image to be treated as a specified-") +
                              std::string("dimensional image.  If not specified, the program tries to ") +
                              std::string("infer the dimensionality from the input image.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("dimensionality");
    option->SetShortName('d');
    option->SetUsageOption(0, "2/3");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  // {
  //   std::string description =
  //     std::string("turn on the option that lets you estimate the learning rate step size only at the beginning of each "
  //                 "level.  * useful as a second stage of fine-scale registration.");

  //   OptionType::Pointer option = OptionType::New();
  //   option->SetLongName("use-estimate-learning-rate-once");
  //   option->SetShortName('l');
  //   option->SetDescription(description);
  //   parser->AddOption(option);
  // }

  {
    std::string description =
      std::string("This option sets the number of images to use to construct the template image.");
    OptionType::Pointer option = OptionType::New();
    option->SetLongName("n-images");
    option->SetShortName('n');
    option->SetUsageOption(0, "10");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description =
      std::string("Four image metrics are available--- ") +
      std::string("GC : global correlation, CC:  ANTS neighborhood cross correlation, MI:  Mutual information, and ") +
      std::string("Demons:  Thirion's Demons (modified mean-squares). ") +
      std::string("Note that the metricWeight is currently not used.  ") +
      std::string("Rather, it is a temporary place holder until multivariate metrics ") +
      std::string("are available for a single stage. ") +
      std::string("The fixed image should be a single time point (eg the average of the time series). ") +
      std::string(
        "By default, this image is not used, the fixed image for correction of each volume is the preceding volume ") +
      std::string("in the time series. See below for the option to use a fixed reference image for all volumes. ") +
      std::string("useGradientFilter specifies whether a smoothing") +
      std::string("filter is applied when estimating the metric gradient.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("metric");
    option->SetShortName('m');
    option->SetUsageOption(
      0,
      "CC[fixedImage,movingImage,metricWeight,radius,<samplingStrategy={Regular,Random}>,<samplingPercentage=[0,1]>,<useGradientFilter=false>]");
    option->SetUsageOption(1,
                           "MI[fixedImage,movingImage,metricWeight,numberOfBins,<samplingStrategy={Regular,Random}>,<"
                           "samplingPercentage=[0,1]>,<useGradientFilter=false>]");
    option->SetUsageOption(2,

                           "Demons[fixedImage,movingImage,metricWeight,radius,<samplingStrategy={Regular,Random}>,<"
                           "samplingPercentage=[0,1]>,<useGradientFilter=false>]");
    option->SetUsageOption(
      3,
      "GC[fixedImage,movingImage,metricWeight,radius,<samplingStrategy={Regular,Random}>,<samplingPercentage=[0,1]>,<useGradientFilter=false>]");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description =
      std::string("use a fixed reference image to correct all volumes, instead of correcting each image ") +
      std::string("to the prior volume in the time series.");
    OptionType::Pointer option = OptionType::New();
    option->SetLongName("useFixedReferenceImage");
    option->SetShortName('u');
    option->SetUsageOption(0, "(0)/1");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string         description = std::string("use the scale estimator to control optimization.");
    OptionType::Pointer option = OptionType::New();
    option->SetLongName("useScalesEstimator");
    option->SetShortName('e');
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description =
      std::string("Several transform options are available.  The gradientStep or") +
      std::string("learningRate characterizes the gradient descent optimization and is scaled appropriately ") +
      std::string("for each transform using the shift scales estimator.  Subsequent parameters are ") +
      std::string("transform-specific and can be determined from the usage. ");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("transform");
    option->SetShortName('t');
    option->SetUsageOption(0, "Affine[gradientStep]");
    option->SetUsageOption(1, "Rigid[gradientStep]");
    option->SetUsageOption(
      2, "GaussianDisplacementField[gradientStep,updateFieldSigmaInPhysicalSpace,totalFieldSigmaInPhysicalSpace]");
    option->SetUsageOption(3, "SyN[gradientStep,updateFieldSigmaInPhysicalSpace,totalFieldSigmaInPhysicalSpace]");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Specify the number of iterations at each level.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("iterations");
    option->SetShortName('i');
    option->SetUsageOption(0, "MxNx0...");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description =
      std::string("Specify the sigma for smoothing at each level. Smoothing may be specified ") +
      std::string("in mm units or voxels with \"AxBxCmm\" or \"AxBxCvox\". No units implies voxels.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("smoothingSigmas");
    option->SetShortName('s');
    option->SetUsageOption(0, "MxNx0...");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description =
      std::string("Specify the shrink factor for the virtual domain (typically the fixed image) at each level.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("shrinkFactors");
    option->SetShortName('f');
    option->SetUsageOption(0, "MxNx0...");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description =
      std::string("Specify the output transform prefix (output format is .nii.gz ).") +
      std::string("Optionally, one can choose to warp the moving image to the fixed space and, if the ") +
      std::string("inverse transform exists, one can also output the warped fixed image.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("output");
    option->SetShortName('o');
    option->SetUsageOption(0, "[outputTransformPrefix,<outputWarpedImage>,<outputAverageImage>]");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Average the input time series image.");
    OptionType::Pointer option = OptionType::New();
    option->SetLongName("average-image");
    option->SetShortName('a');
    option->SetUsageOption(0, "<timeseries>");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Write the low-dimensional 3D transforms to a 4D displacement field.");
    OptionType::Pointer option = OptionType::New();
    option->SetLongName("write-displacement");
    option->SetShortName('w');
    option->SetUsageOption(0, "(0)/1");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string         description = std::string("Histogram match the moving images to the reference image.");
    OptionType::Pointer option = OptionType::New();
    option->SetLongName("use-histogram-matching");
    option->SetUsageOption(0, "0/(1)");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Use a fixed seed for random number generation. ") +
                              std::string("By default, the system clock is used to initialize the seeding. ") +
                              std::string("The fixed seed can be any nonzero int value.");
    OptionType::Pointer option = OptionType::New();
    option->SetLongName("random-seed");
    option->SetUsageOption(0, "seedValue");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Several interpolation options are available in ITK. ") +
                              std::string("The above are available (default Linear).");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("interpolation");
    // n is already in use by --n-images. Unfortunately flag shortname is inconsistent with antsApplyTransforms.
    option->SetShortName('p');
    option->SetUsageOption(0, "Linear");
    option->SetUsageOption(1, "NearestNeighbor");
    option->SetUsageOption(2, "BSpline[<order=3>]");
    option->SetUsageOption(3, "BlackmanWindowedSinc");
    option->SetUsageOption(4, "CosineWindowedSinc");
    option->SetUsageOption(5, "WelchWindowedSinc");
    option->SetUsageOption(6, "HammingWindowedSinc");
    option->SetUsageOption(7, "LanczosWindowedSinc");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Verbose output.");

    OptionType::Pointer option = OptionType::New();
    option->SetShortName('v');
    option->SetLongName("verbose");
    option->SetUsageOption(0, "(0)/1");
    option->SetDescription(description);
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Print the help menu (short version).");

    OptionType::Pointer option = OptionType::New();
    option->SetShortName('h');
    option->SetDescription(description);
    option->AddFunction(std::string("0"));
    parser->AddOption(option);
  }

  {
    std::string description = std::string("Print the help menu.");

    OptionType::Pointer option = OptionType::New();
    option->SetLongName("help");
    option->SetDescription(description);
    option->AddFunction(std::string("0"));
    parser->AddOption(option);
  }
}

// entry point for the library; parameter 'args' is equivalent to 'argv' in (argc,argv) of commandline parameters to
// 'main()'
int
antsMotionCorr(std::vector<std::string> args, std::ostream * /*out_stream = nullptr */)
{
  // put the arguments coming in as 'args' into standard (argc,argv) format;
  // 'args' doesn't have the command name as first, argument, so add it manually;
  // 'args' may have adjacent arguments concatenated into one argument,
  // which the parser should handle
  args.insert(args.begin(), "antsMotionCorr");

  int     argc = args.size();
  char ** argv = new char *[args.size() + 1];
  for (unsigned int i = 0; i < args.size(); ++i)
  {
    // allocate space for the string plus a null character
    argv[i] = new char[args[i].length() + 1];
    std::strncpy(argv[i], args[i].c_str(), args[i].length());
    // place the null character in the end
    argv[i][args[i].length()] = '\0';
  }
  argv[argc] = nullptr;
  // class to automatically cleanup argv upon destruction
  class Cleanup_argv
  {
  public:
    Cleanup_argv(char ** argv_, int argc_plus_one_)
      : argv(argv_)
      , argc_plus_one(argc_plus_one_)
    {}

    ~Cleanup_argv()
    {
      for (unsigned int i = 0; i < argc_plus_one; ++i)
      {
        delete[] argv[i];
      }
      delete[] argv;
    }

  private:
    char **      argv;
    unsigned int argc_plus_one;
  };
  Cleanup_argv cleanup_argv(argv, argc + 1);

  // antscout->set_stream( out_stream );

  itk::ants::CommandLineParser::Pointer parser = itk::ants::CommandLineParser::New();

  parser->SetCommand(argv[0]);

  std::string commandDescription =
    std::string("antsMotionCorr = motion correction.  This program is a user-level ") +
    std::string("registration application meant to utilize classes in ITK v4.0 or greater. The user can specify ") +
    std::string("any number of \"stages\" where a stage consists of a transform; an image metric; ") +
    std::string("and iterations, shrink factors, and smoothing sigmas for each level. ") +
    std::string(
      "Specialized for 4D time series data: fixed image is 3D, moving image should be the 4D time series. ") +
    std::string("Fixed image is a reference space or time slice. ") +
    std::string("To create a reference image from the time series, use the -a option.");
  parser->SetCommandDescription(commandDescription);
  antsMotionCorrInitializeCommandLineOptions(parser);

  if (parser->Parse(argc, argv) == EXIT_FAILURE)
  {
    return EXIT_FAILURE;
  }

  if (argc < 2 || parser->Convert<bool>(parser->GetOption("help")->GetFunction()->GetName()))
  {
    parser->PrintMenu(std::cout, 5, false);
    if (argc < 2)
    {
      return EXIT_FAILURE;
    }
    return EXIT_SUCCESS;
  }
  else if (parser->Convert<bool>(parser->GetOption('h')->GetFunction()->GetName()))
  {
    parser->PrintMenu(std::cout, 5, true);
    return EXIT_SUCCESS;
  }

  // Get dimensionality
  unsigned int dimension = 3;

  itk::ants::CommandLineParser::OptionType::Pointer dimOption = parser->GetOption("dimensionality");
  if (dimOption && dimOption->GetNumberOfFunctions())
  {
    dimension = parser->Convert<unsigned int>(dimOption->GetFunction(0)->GetName());
  }
  else
  {
    std::cerr << "Image dimensionality not specified.  See command line option --dimensionality" << std::endl;
    return EXIT_FAILURE;
  }

  switch (dimension)
  {
    case 2:
    {
      return ants_motion<2>(parser);
    }
    break;
    case 3:
    {
      return ants_motion<3>(parser);
    }
    break;
    default:
      std::cerr << "Unsupported dimension" << std::endl;
      return EXIT_FAILURE;
  }
  return EXIT_SUCCESS;
}

} // namespace ants