File: commands.py

package info (click to toggle)
montage-wrapper 0.9.9-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 1,092 kB
  • sloc: python: 8,325; makefile: 116; ansic: 88
file content (2311 lines) | stat: -rw-r--r-- 76,120 bytes parent folder | download | duplicates (2)
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
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
import subprocess
import shlex

from . import status
from .commands_extra import *
from .mpi import _get_mpi_command

def mAdd(images_table, template_header, out_image, img_dir=None,
          no_area=False, type=None, exact=False, debug_level=None,
          status_file=None, mpi=False, n_proc=8):
    '''
    Coadd the reprojected images in an input list to form an output mosaic
    with FITS header keywords specified in a header file. Creates two output
    files, one containing the coadded pixel values, and the other containing
    coadded pixel area values. The pixel area values can be used as a
    weighting function if the output pixel values are themselves to be coadded
    with other projected images, and may also be used in validating the
    fidelity of the output pixel values.

    Parameters
    ----------

    images_table : str
        ASCII table (generated by mImgtbl) containing metadata for all images
        to be coadded.

    template_header : str
        FITS header template to be used in generation of output FITS

    out_image : str
        Name of output FITS image.

    img_dir : str, optional
        Specifies path to directory containing reprojected images. If the
        img_dir option is not included, mAdd will look for the input images in
        the current working directory.

    no_area : bool, optional
        Co-addition ignores weighting by pixel areas and performs coaddition
        based only on pixel postions. Will not output an area image for the
        output image.

    type : str, optional
        Select type of averaging to be done on accumulated pixel values
        (either mean or median). To generate a map showing counts of how many
        times each pixel was overlapped by the input images, use count.

    exact : bool, optional
        Enables exact size mode. The output image will match the header
        template exactly, instead of shrinking the output to fit the data.

    debug_level : int, optional
        Turns on debugging to the specified level (1-3).

    status_file : str, optional
        mAdd output and errors will be written to status_file instead of
        stdout.

    mpi : bool, optional
        If set to True, will use the MPI-enabled versions of the Montage
        executable.

    n_proc : int, optional
        If mpi is set to True, n_proc is the number of processes to run
        simultaneously (default is 8)
    '''
    if mpi:
        command = _get_mpi_command(executable="mAddMPI", n_proc=n_proc)
    else:
        command = "mAdd"
    if img_dir:
        command += " -p %s" % str(img_dir)
    if no_area:
        command += " -n"
    if type:
        command += " -a %s" % str(type)
    if exact:
        command += " -e"
    if debug_level:
        command += " -d %s" % str(debug_level)
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(images_table)
    command += " " + str(template_header)
    command += " " + str(out_image)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mAdd", p.stdout.read().strip())


def mAddExec(images_table, template_header, tile_dir, out_image, img_dir=None,
          no_area=False, type=None, exact=False, debug_level=None,
          status_file=None, mpi=False, n_proc=8):
    '''
    Builds a series of outputs (which together make up a tiled output) through
    multiple executions of the mAdd modules.

    Parameters
    ----------

    images_table : str
        ASCII table (generated by mImgtbl) containing metadata for all images
        to be coadded.

    template_header : str
        FITS header template to be used in generation of output FITS

    tile_dir : str
        Directory to contain output tile images and header templates

    out_image : str
        Prefix for output tile images

    img_dir : str, optional
        Specifies path to directory containing reprojected images. If the
        img_dir option is not included, mAdd will look for the input images in
        the current working directory.

    no_area : bool, optional
        Co-addition ignores weighting by pixel areas and performs coaddition
        based only on pixel postions. Will not output an area image for the
        output image.

    type : str, optional
        Select type of averaging to be done on accumulated pixel values
        (either mean or median).

    exact : bool, optional
        Enables exact size mode. The output image will match the header
        template exactly, instead of shrinking the output to fit the data.

    debug_level : int, optional
        Turns on debugging to the specified level (1-3).

    status_file : str, optional
        mAdd output and errors will be written to status_file instead of
        stdout.

    mpi : bool, optional
        If set to True, will use the MPI-enabled versions of the Montage
        executable.

    n_proc : int, optional
        If mpi is set to True, n_proc is the number of processes to run
        simultaneously (default is 8)
    '''
    if mpi:
        command = _get_mpi_command(executable="mAddExecMPI", n_proc=n_proc)
    else:
        command = "mAddExec"
    if img_dir:
        command += " -p %s" % str(img_dir)
    if no_area:
        command += " -n"
    if type:
        command += " -a %s" % str(type)
    if exact:
        command += " -e"
    if debug_level:
        command += " -d %s" % str(debug_level)
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(images_table)
    command += " " + str(template_header)
    command += " " + str(tile_dir)
    command += " " + str(out_image)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mAddExec", p.stdout.read().strip())


def mArchiveExec(region_table, debug_level=None):
    '''
    Given a table of archive images (generated by mArchiveList), calls
    mArchiveGet on each one in sequence to retrieve all the files into the
    current directory.

    Parameters
    ----------

    region_table : str
        Table of archive images, generated by mArchiveList.

    debug_level : int, optional
        Prints out additional debugging information; in this version, the only
        supported level is 1.
    '''
    command = "mArchiveExec"
    if debug_level:
        command += " -d %s" % str(debug_level)
    command += " " + str(region_table)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mArchiveExec", p.stdout.read().strip())


def mArchiveGet(remote_ref, local_file, debug=False, raw=False):
    '''
    Retrieve a single FITS image from a remote archive, using a basic URL GET
    but with a structured output.

    Parameters
    ----------

    remote_ref : str
        URL of remote FITS file to retrieve (should be in quotes). See
        mArchiveList for more information.

    local_file : str
        Full path/filename of the retrieved file.

    debug : bool, optional
        Print additional debugging information.

    raw : bool, optional
        "Raw" mode - use a raw HTTP GET (no "HTTP/1.1" etc in the header);
        necessary for communication with some servers.
    '''
    command = "mArchiveGet"
    if debug:
        command += " -d"
    if raw:
        command += " -r"
    command += ' "' + str(remote_ref) + '"'
    command += " " + str(local_file)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mArchiveGet", p.stdout.read().strip())


def mArchiveList(survey, band, object_or_location, width, height, out_file):
    '''
    Given a location on the sky, archive name, and size in degrees, contact
    the IRSA server to retrieve a list of archive images.  The list contains
    enough information to support mArchiveGet downloads.

    Parameters
    ----------

    survey : str
        Can be one of: 2MASS DSS SDSS DPOSS

    band : str
        Case insensitive - can be one of: (2MASS) j, h, k (SDSS) u, g, r, i, z
        (DPOSS) f, j, n (DSS) DSS1, DSS1R, DSS1B, DSS2, DSS2B, DSS2R, DSS2IR

    object_or_location : str
        Object name or coordinate string to be resolved by NED (if string
        includes spaces, must be surrounded by double quotes)

    width : float
        Width of area of interest, in degrees

    height : float
        Height of area of interest, in degrees

    out_file : str
        Path to output table
    '''
    command = "mArchiveList"
    command += " " + str(survey)
    command += " " + str(band)
    command += ' "' + str(object_or_location) + '"'
    command += " " + str(width)
    command += " " + str(height)
    command += " " + str(out_file)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mArchiveList", p.stdout.read().strip())


def mBackground(in_image, out_image, A, B, C, debug_level=None, no_area=False,
          status_file=None):
    '''
    Remove a background plane from a FITS image.  The background correction
    applied to the image is specified as Ax+By+C, where (x,y) is the pixel
    coordinate using the image center as the origin, and (A,B,C) are the
    background plane parameters specified as linear coefficients. To run in
    'table' mode, see mBackground_tab.

    Parameters
    ----------

    in_image : str
        Input FITS file

    out_image : str
        Output FITS file

    A, B, C : str
        Corrections (as given by mFitplane or mFitExec)

    debug_level : int, optional
        Turns on debugging to the specified level.

    no_area : bool, optional
        Indicates that no area images are present (assumes equal weighting for
        each data pixel)

    status_file : str, optional
        mBackground output and errors will be written to status_file instead
        of stdout.
    '''
    command = "mBackground"
    if debug_level:
        command += " -d %s" % str(debug_level)
    if no_area:
        command += " -n"
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(in_image)
    command += " " + str(out_image)
    command += " " + str(A)
    command += " " + str(B)
    command += " " + str(C)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mBackground", p.stdout.read().strip())


def mBackground_tab(in_image, out_image, images_table, corrections_table,
          debug_level=None, no_area=False, status_file=None):
    '''
    Remove a background plane from a FITS image.  The background correction
    applied to the image is specified as Ax+By+C, where (x,y) is the pixel
    coordinate using the image center as the origin, and (A,B,C) are the
    background plane parameters specified as linear coefficients. This method
    runs mBackground_tab in 'table' mode.

    Parameters
    ----------

    in_image : str
        Input FITS file

    out_image : str
        Output FITS file

    images_table : str
        Image metadata table to retrieve the filenames of images.

    corrections_table : str
        Table of corrections (from mFitplane and mFitExec) to apply to the
        corresponding image (from images_table).

    debug_level : int, optional
        Turns on debugging to the specified level.

    no_area : bool, optional
        Indicates that no area images are present (assumes equal weighting for
        each data pixel)

    status_file : str, optional
        mBackground_tab output and errors will be written to status_file
        instead of stdout.
    '''
    command = "mBackground_tab"
    if debug_level:
        command += " -d %s" % str(debug_level)
    if no_area:
        command += " -n"
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(in_image)
    command += " " + str(out_image)
    command += " " + str(images_table)
    command += " " + str(corrections_table)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mBackground_tab", p.stdout.read().strip())


def mBestImage(images_table, ra, dec, debug=False):
    '''
    Given a list of images and a position on the sky, determine which image
    covers the location "best" (i.e., the one where the position is farthest
    from the nearest edge).

    Parameters
    ----------

    images_table : str
        Input table of image metadata (as generated by mImgtbl).

    ra : float
        RA of location of interest (in degrees)

    dec : float
        Declination of location of interest (in degrees)

    debug_level : int, optional
        Turn on debugging to the specified level (1 or 2)
    '''
    command = "mBestImage"
    if debug:
        command += " -d"
    command += " " + str(images_table)
    command += " " + str(ra)
    command += " " + str(dec)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mBestImage", p.stdout.read().strip())


def mBgExec(images_table, corrections_table, corr_dir, proj_dir=None,
          status_file=None, debug=False, no_area=False, mpi=False, n_proc=8):
    '''
    Runs mBackground on all the images in a metadata table, using the
    corrections generated by mBgModel.

    Parameters
    ----------

    images_table : str
        Image metadata table generated by mImgtbl.

    corrections_table : str
        Table of corrections generated by mFitExec

    corr_dir : str
        Directory where output images should be written

    proj_dir : str, optional
        Specifies the path to the directory containing the projected images.

    status_file : str, optional
        Writes output message to status_file instead of to stdout

    debug : bool, optional
        Turns on debugging

    no_area : bool, optional
        Indicates that no area images are present (assumes equal weighting for
        each pixel)

    mpi : bool, optional
        If set to True, will use the MPI-enabled versions of the Montage
        executable.

    n_proc : int, optional
        If mpi is set to True, n_proc is the number of processes to run
        simultaneously (default is 8)
    '''
    if mpi:
        command = _get_mpi_command(executable="mBgExecMPI", n_proc=n_proc)
    else:
        command = "mBgExec"
    if proj_dir:
        command += " -p %s" % str(proj_dir)
    if status_file:
        command += " -s %s" % str(status_file)
    if debug:
        command += " -d"
    if no_area:
        command += " -n"
    command += " " + str(images_table)
    command += " " + str(corrections_table)
    command += " " + str(corr_dir)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mBgExec", p.stdout.read().strip())


def mBgModel(images_table, fits_table, corrections_table, n_iter=None,
          level_only=False, debug_level=None, ref_img=None, status_file=None):
    '''
    mBgModel is a modelling/fitting program.  It uses the image-to-image
    difference parameter table created by mFitExec to interactively determine
    a set of corrections to apply to each image in order to achieve a "best"
    global fit.

    Parameters
    ----------

    images_table : str
        Image metadata table generated by mImgtbl.

    fits_table : str
        Plane fitting table generated by mFitExec.

    corrections_table : str
        Output table of background corrections

    n_iter : int, optional
        Number of iterations (without option, defaults to 5000). Can be
        between 1 and 32767.

    level_only : bool, optional
        Calculate level adjustments only (ie, don't attempt to match the
        slopes)

    debug_level : int, optional
        Turns on debugging to the specified level (1-3).

    ref_img : str, optional
        Turns on additional debugging for the nth image in images_table.

    status_file : str, optional
        mBgModel output and errors are written to status_file instead of to
        stdout.
    '''
    command = "mBgModel"
    if n_iter:
        command += " -i %s" % str(n_iter)
    if level_only:
        command += " -l"
    if debug_level:
        command += " -d %s" % str(debug_level)
    if ref_img:
        command += " -r %s" % str(ref_img)
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(images_table)
    command += " " + str(fits_table)
    command += " " + str(corrections_table)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mBgModel", p.stdout.read().strip())


def mCatMap(in_table, out_image, template_header, column=None, ref_mag=None,
          debug_level=None, size=None):
    '''
    mCatMap is a point-source imaging program.  The user defines a general
    output FITS image, and its pixels are populated from a table of point
    sources.  The source fluxes (or just source counts) from the table are
    added into the appropriate pixel to create an output image.

    Parameters
    ----------

    in_table : str
        Input table of source metadata.

    out_image : str
        Path of output FITS file.

    template_header : str
        ASCII header template defining output FITS file.

    column : str, optional
        Name of the table column that contains flux levels. If not specified,
        pixels will be populated with source counts rather than summed flux
        values.

    ref_mag : float, optional
        Set a reference magnitude to use when calculating fluxes.

    debug_level : int, optional
        Turn on debugging to the specified level (1-3)

    size : int, optional
        Set a spread size for point sources (default is to use no spread).
        Allowed values are 3 or 5.
    '''
    command = "mCatMap"
    if column:
        command += " -c %s" % str(column)
    if ref_mag:
        command += " -m %s" % str(ref_mag)
    if debug_level:
        command += " -d %s" % str(debug_level)
    if size:
        command += " -w %s" % str(size)
    command += " " + str(in_table)
    command += " " + str(out_image)
    command += " " + str(template_header)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mCatMap", p.stdout.read().strip())


def mConvert(in_image, out_image, debug_level=None, status_file=None,
          bitpix=None, min_val=None, max_val=None, blank_value=None):
    '''
    mConvert changes the datatype of an image.  When converting to floating
    point, no additional information is needed.  However, when converting from
    higher precision (e.g. 64-bit floating point) to lower (e.g. 16-bit
    integer), scaling information is necessary.  This can be given explicitly
    by the user or guessed by the program.

    Parameters
    ----------

    in_image : str
        Input image filename

    out_image : str
        Output image filename.

    debug_level : int, optional
        Turns on debugging to the specified level (1-3).

    status_file : str, optional
        mBgModel output and errors are written to status_file instead of to
        stdout.

    bitpix : int, optional
        BITPIX value for the ouput FITS file (default is -64). Possible values
        are: 8 (character or unsigned binary integer), 16 (16-bit integer), 32
        (32-bit integer), -32 (single precision floating point), -64 (double
        precision floating point).

    min_val : int, optional
        Pixel data value in the input image which should be treated as a
        minimum (value of 0) in the output image when converting from floating
        point to integer (default for BITPIX 8: 0; BITPIX 16: -32767; BITPIX
        32: -2147483647

    max_val : int, optional
        Pixel data value in the input image which should be treated as a
        maximum (value of 255 or 32768) in the output image when converting
        from floating point to integer (Default for BITPIX 8: 255; BITPIX 16:
        32768; BITPIX 32: 2147483648)

    blank_value : int, optional
        If converting down to an integer scale: value to be used in the output
        image to represent blank pixels (NaN) from the input image. Default
        value is min_val.
    '''
    command = "mConvert"
    if debug_level:
        command += " -d %s" % str(debug_level)
    if status_file:
        command += " -s %s" % str(status_file)
    if bitpix:
        command += " -b %s" % str(bitpix)
    if min_val:
        command += " -min %s" % str(min_val)
    if max_val:
        command += " -max %s" % str(max_val)
    if blank_value:
        command += " -blank %s" % str(blank_value)
    command += " " + str(in_image)
    command += " " + str(out_image)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mConvert", p.stdout.read().strip())


def mDiff(in_image_1, in_image_2, out_image, template_header,
          debug_level=None, no_area=False, status_file=None):
    '''
    mDiff calculates a simple difference between a single pair of overlapping
    images. This is meant for use on reprojected images where the pixels
    already line up exactly. mDiff analyzes an image metadata table to
    determine a list of overlapping images.  Each image is compared with every
    other image to determine all overlapping image pairs.  A pair of images
    are deemed to overlap if any pixel around the perimeter of one image falls
    within the boundary of the other image.

    Parameters
    ----------

    in_image_1 : str
        First input FITS file (Also needs area image in1_area_image, or use
        the no_area option)

    in_image_2 : str
        Second input FITS file.(Also needs area image in2_area_image, or use
        the no_area option)

    out_image : str
        Difference FITS image to be generated.

    template_header : str
        FITS header template used to generate output image.

    debug_level : int, optional
        Turns on debugging to the specified level (1-4).

    no_area : bool, optional
        No-area-images option. Creates difference image without requiring
        pixel area FITS image

    status_file : str, optional
        Output and errors are sent to status_file instead of to stdout
    '''
    command = "mDiff"
    if debug_level:
        command += " -d %s" % str(debug_level)
    if no_area:
        command += " -n"
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(in_image_1)
    command += " " + str(in_image_2)
    command += " " + str(out_image)
    command += " " + str(template_header)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mDiff", p.stdout.read().strip())


def mDiffExec(diffs_table, template_header, diff_dir, proj_dir=None,
          debug=False, no_area=False, status_file=None, mpi=False, n_proc=8):
    '''
    Runs mDiff on all the pairs identified by mOverlaps.

    Parameters
    ----------

    diffs_table : str
        Table generated by mOverlaps for the images in proj_dir.

    template_header : str
        FITS header template for output files.

    diff_dir : str
        Path to output files.

    proj_dir : str, optional
        Specifies path to the directory containing reprojected input images.

    debug : bool, optional
        Turns on debugging.

    no_area : bool, optional
        No-area-images option. Creates difference image without requiring
        _area FITS images

    status_file : str, optional
        Output and errors are sent to status_file instead of to stdout

    mpi : bool, optional
        If set to True, will use the MPI-enabled versions of the Montage
        executable.

    n_proc : int, optional
        If mpi is set to True, n_proc is the number of processes to run
        simultaneously (default is 8)
    '''
    if mpi:
        command = _get_mpi_command(executable="mDiffExecMPI", n_proc=n_proc)
    else:
        command = "mDiffExec"
    if proj_dir:
        command += " -p %s" % str(proj_dir)
    if debug:
        command += " -d"
    if no_area:
        command += " -n"
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(diffs_table)
    command += " " + str(template_header)
    command += " " + str(diff_dir)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mDiffExec", p.stdout.read().strip())


def mDiffFitExec(diffs_table, fits_table, diff_dir, debug=False,
          status_file=None):
    '''
    Using the table of overlaps found by mOverlaps, mDiffFitExec runs both
    mDiff and mFitplane for each record.  The fitting parameters are written
    to a file to be used by mBgModel.

    Parameters
    ----------

    diffs_table : str
        Overlap table generated by mOverlaps, the last column of which
        contains the filenames of the difference images generated by
        mDiffExec.

    fits_table : str
        Output table of difference paramaters.

    diff_dir : str
        Directory containing difference images.

    debug : bool, optional
        Turns on debugging

    status_file : str, optional
        Writes output message to status_file instead of to stdout
    '''
    command = "mDiffFitExec"
    if debug:
        command += " -d"
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(diffs_table)
    command += " " + str(fits_table)
    command += " " + str(diff_dir)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mDiffFitExec", p.stdout.read().strip())


def mExec(survey, band, raw_dir=None, n_tile_x=None, n_tile_y=None,
          level_only=False, keep=False, remove=False, output_image=None,
          debug_level=None, region_header=None, header=None,
          workspace_dir=None):
    '''
    The mExec module is a mosaicking executive for 2MASS, SDSS, and DSS data.
    It includes remote data and metadata access.  Alternatively, users can
    mosaic a set of data already on disk.

    Parameters
    ----------

    survey, band : str
        If not mosaicking user-provided data (raw_dir option), must select one
        of the following combinations of survey and band: 2MASS [j, h, k] SDSS
        [u, g, r, i, z] DSS [DSS1, DSS1R, DSS1B, DSS2, DSS2B, DSS2R, DSS2IR]

    raw_dir : str, optional
        Provide path to directory containing original ("raw") data which will
        be reprojected and mosaicked. Not necessary if using mExec to retrieve
        remote data from the 2MASS, SDSS or DSS surveys.

    n_tile_x : int, optional
        Number of output tiles to create along the X-axis - default is 1 for a
        single mosaicked image.

    n_tile_y : int, optional
        Number of output tiles to create along the Y-axis - default is equal
        to n_tile_x.

    level_only : bool, optional
        "Level-only" option (see mBgModel)

    keep : bool, optional
        If retrieving data from a remote archive, the "keep" option will leave
        the original data products on disk after generating a mosaic. Without
        this option, raw data will be deleted (unless it was provided by the
        user with the "-r" option).

    remove : bool, optional
        Remove all temporary files and intermediate data products. Note: if
        not using the '-o' option to specify an output file, this will also
        remove mosaic_image.

    output_image : str, optional
        Provide your own filename for the output mosaic. Default filename is
        "mosaic_image."

    debug_level : int, optional
        Print out additional debugging information (levels 1-4)

    region_header : str, optional
        Path to header template used to create mosaic.

    header : str, optional
        Provide header template as text input rather than point to a file; see
        sample shell script that makes use of this option.

    workspace_dir : str, optional
        Directory where intermediate files will be created. If no workspace is
        given, a unique local subdirectory will be created (e.g.;
        ./MOSAIC_AAAaa17v)
    '''
    command = "mExec"
    if raw_dir:
        command += " -r %s" % str(raw_dir)
    if n_tile_x:
        command += " -n %s" % str(n_tile_x)
    if n_tile_y:
        command += " -m %s" % str(n_tile_y)
    if level_only:
        command += " -l"
    if keep:
        command += " -k"
    if remove:
        command += " -c"
    if output_image:
        command += " -o %s" % str(output_image)
    if debug_level:
        command += " -d %s" % str(debug_level)
    if region_header:
        command += " -f %s" % str(region_header)
    if header:
        command += " -h %s" % str(header)
    command += " " + str(survey)
    command += " " + str(band)
    if workspace_dir:
        command += " %s" % str(workspace_dir)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mExec", p.stdout.read().strip())


def mFitExec(diffs_table, fits_table, diff_dir, debug=False, status_file=None,
          mpi=False, n_proc=8):
    '''
    Runs mFitplane on all the difference images identified by mOverlaps and
    generated by mDiff or mDiffExec. mFitExec creates a table of image-to-
    image difference parameters.

    Parameters
    ----------

    diffs_table : str
        Overlap table generated by mOverlaps, the last column of which
        contains the filenames of the difference images generated by
        mDiffExec.

    fits_table : str
        Output table of difference paramaters.

    diff_dir : str
        Directory containing difference images.

    debug : bool, optional
        Turns on debugging

    status_file : str, optional
        Writes output message to status_file instead of to stdout

    mpi : bool, optional
        If set to True, will use the MPI-enabled versions of the Montage
        executable.

    n_proc : int, optional
        If mpi is set to True, n_proc is the number of processes to run
        simultaneously (default is 8)
    '''
    if mpi:
        command = _get_mpi_command(executable="mFitExecMPI", n_proc=n_proc)
    else:
        command = "mFitExec"
    if debug:
        command += " -d"
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(diffs_table)
    command += " " + str(fits_table)
    command += " " + str(diff_dir)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mFitExec", p.stdout.read().strip())


def mFitplane(in_image, border=None, debug_level=None, status_file=None):
    '''
    Uses least squares to fit a plane (excluding outlier pixels) to an image.
    It is used on the difference images generated using mDiff or mDiffExec.

    Parameters
    ----------

    in_image : str
        Input FITS file is a difference file between two other FITS files, as
        can be generated using mDiff.

    border : int, optional
        Number of border pixels to ignore at edges of image.

    debug_level : int, optional
        Turns on debugging to the specified level (1-3).

    status_file : str, optional
        Output and errors are written to status_file instead of stdout.
    '''
    command = "mFitplane"
    if border:
        command += " -b %s" % str(border)
    if debug_level:
        command += " -d %s" % str(debug_level)
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(in_image)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mFitplane", p.stdout.read().strip())


def mFixNaN(in_image, out_image, debug_level=None, nan_value=None,
          min_blank=None, max_blank=None):
    '''
    Converts NaNs found in the image to some other value (given by the user),
    or converts a range of supplied values into NaNs.

    Parameters
    ----------

    in_image : str
        Input FITS image file

    out_image : str
        Path of output FITS file. To run in "count" mode without creating an
        output file, use a dash ("-") for this argument.

    debug_level : int, optional
        Turn on debugging to the specified level (1-3)

    nan_value : float, optional
        Value to use in place of any NaNs

    min_blank, max_blank : str, optional
        If the nan_value option is not used, mFixNaN will replace all pixel
        values between min_blank and max_blank with NaN.
    '''
    command = "mFixNaN"
    if debug_level:
        command += " -d %s" % str(debug_level)
    if nan_value:
        command += " -v %s" % str(nan_value)
    command += " " + str(in_image)
    command += " " + str(out_image)
    if min_blank and max_blank:
        command += " %s" % str(min_blank)
        command += " %s" % str(max_blank)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mFixNaN", p.stdout.read().strip())


def mFlattenExec(images_table, flat_dir, img_dir=None, debug=False,
          no_area=False, status_file=None):
    '''
    Runs both mFitPlane and mBackground on a set of images.

    Parameters
    ----------

    images_table : str
        Metadata table (generated by mImgtbl) describing images to be
        flattened.

    flat_dir : str
        Path to directory where output files should be created.

    img_dir : str, optional
        Specifies path to directory containing images to be flattened.

    debug : bool, optional
        Turns on debugging.

    no_area : bool, optional
        No-area-images option, indicating that mFlattenExec should not require
        area images for all the input FITS images.

    status_file : str, optional
        Output and errors are sent to status_file instead of to stdout
    '''
    command = "mFlattenExec"
    if img_dir:
        command += " -p %s" % str(img_dir)
    if debug:
        command += " -d"
    if no_area:
        command += " -n"
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(images_table)
    command += " " + str(flat_dir)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mFlattenExec", p.stdout.read().strip())


def mGetHdr(in_image, img_header, debug=False, hdu=None, status_file=None):
    '''
    Reads in the header from a FITS image and prints it out to a text file.

    Parameters
    ----------

    in_image : str
        Path to FITS image from which to retrieve the header.

    img_header : str
        Path to text file where FITS header should be written.

    debug : bool, optional
        Turns on debugging.

    hdu : int, optional
        Retrieve the header from the Fits extention given by hdu. "0"
        indicates the primary FITS extension, and is the default used by
        mGetHdr.

    status_file : str, optional
        Output and errors are sent to status_file instead of to stdout
    '''
    command = "mGetHdr"
    if debug:
        command += " -d"
    if hdu:
        command += " -h %s" % str(hdu)
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(in_image)
    command += " " + str(img_header)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mGetHdr", p.stdout.read().strip())


def mHdr(object_or_location, width, out_file, system=None, equinox=None,
          height=None, pix_size=None, rotation=None):
    '''
    Connects to the IRSA service HdrTemplate to create a header template based
    on a location, size, resolution and rotation.

    Parameters
    ----------

    object_or_location : str
        Object string or coordinate location

    width : float
        Width (x-axis) of area

    out_file : str
        Path to output header template

    system : str, optional
        Specify a coordinate system. Can be one of: "equatorial" or "eq"
        (default), "ecliptic" or "ec" "galactic", "ga", "supergalactic" or
        "sgal"

    equinox : str, optional
        Specify an equinox. Default is 2000.0

    height : float, optional
        Height (y-axis) of area in degrees. Default is equal to width

    pix_size : float, optional
        Size of a pixel (in arcsec); default is 1

    rotation : float, optional
        Rotation of image; default is 0
    '''
    command = "mHdr"
    if system:
        command += " -s %s" % str(system)
    if equinox:
        command += " -e %s" % str(equinox)
    if height:
        command += " -h %s" % str(height)
    if pix_size:
        command += " -p %s" % str(pix_size)
    if rotation:
        command += " -r %s" % str(rotation)
    command += ' "' + str(object_or_location) + '"'
    command += " " + str(width)
    command += " " + str(out_file)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mHdr", p.stdout.read().strip())


def mHdrCheck(in_image, status_file=None):
    '''
    mHdrCheck reads in the header from a FITS image (or an ASCII header
    template file) and checks to see if any header lines are invalid.  If it
    finds one, it will print out a message stating which keyword is invalid
    and exit before checking the rest of the header.  It will not report on
    multiple invalid values.  If all value are correct, mHdrCheck will print
    out a "Valid FITS/WCS" message.

    Parameters
    ----------

    in_image : str
        Path of FITS file to be validated.

    status_file : str, optional
        Output and errors are sent to status_file instead of to stdout
    '''
    command = "mHdrCheck"
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(in_image)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mHdrCheck", p.stdout.read().strip())


def mHdrtbl(directory, images_table, recursive=False, corners=False,
          debug=False, output_invalid=False, status_file=None, img_list=None):
    '''
    mHdrtbl operates in a fashion similar to mImgtbl, but is used on a set of
    header template files instead of FITS images.

    Parameters
    ----------

    directory : str
        Path to directory containing set of input header templates.

    images_table : str
        Path of output metadata table.

    recursive : bool, optional
        mHdrtbl can also be used as a standalone program to gather image
        metadata for other purposes (to populate a database, as a basis for
        spatial coverage searches, etc.) In this case it is often desirable to
        collect information on all the files in a directory tree recursively.
        The recursive option instructs mHdrtbl to search the given directory
        and all its subdirectories recursively.

    corners : bool, optional
        The corners option in mHdrtbl will cause eight extra columns to be
        added to the output metadata table containing the RA, Dec coordinates
        (ra1, dec1, ... ra4, dec4) of the image corners. The output is always
        Equatorial J2000, even if the input is some other system. This has
        been done to make the metadata uniform so that it can easily be used
        for coverage searches, etc. The corners option is not needed for
        normal Montage processing.

    debug : bool, optional
        Turn on debugging

    output_invalid : bool, optional
        When this option is set, mHdrtbl will explicitly output each header
        file it finds that does not appear to be valid, along with information
        on the error.

    status_file : str, optional
        Output and errors are written to status_file instead of being written
        to stdout.

    img_list : str, optional
        mHdrtbl will only process files with names specified in table
        img_list, ignoring any other files in the directory.
    '''
    command = "mHdrtbl"
    if recursive:
        command += " -r"
    if corners:
        command += " -c"
    if debug:
        command += " -d"
    if output_invalid:
        command += " -b"
    if status_file:
        command += " -s %s" % str(status_file)
    if img_list:
        command += " -t %s" % str(img_list)
    command += " " + str(directory)
    command += " " + str(images_table)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mHdrtbl", p.stdout.read().strip())


def mImgtbl(directory, images_table, recursive=False, corners=False,
          include_area=False, debug=False, output_invalid=False,
          status_file=None, fieldlist=None, img_list=None):
    '''
    mImgtbl extracts the FITS header geometry information from a set of files
    and creates an ASCII image metadata table which is used by several of the
    other programs.  It only collects data from headers that comply with the
    FITS standard, but reports a count of images that fail that check.

    Parameters
    ----------

    directory : str
        Path to directory containing set of input FITS files.

    images_table : str
        Path of output metadata table.

    recursive : bool, optional
        mImgtbl can also be used as a standalone program to gather image
        metadata for other purposes (to populate a database, as a basis for
        spatial coverage searches, etc.) In this case it is often desirable to
        collect information on all the files in a directory tree recursively.
        The recursive option instructs mImgtbl to search the given directory
        and all its subdirectories recursively.

    corners : bool, optional
        The corners option in mImgtbl will cause eight extra columns to be
        added to the output metadata table containing the RA, Dec coordinates
        (ra1, dec1, ... ra4, dec4) of the image corners. The output is always
        Equatorial J2000, even if the input is some other system. Though not
        required for the core processing modules, we recommend using this
        option, as some of the utilities may require corner locations to
        function properly.

    include_area : bool, optional
        By default, mImgtbl ignores FITS files with names ending in _area
        (i.e. name_area_image), assuming them to be Montage-created area
        images. If you want to generate information on these images, or if you
        have images with _area in the title other than those generated by
        Montage, you should turn on this option to force mImgtbl to look at
        all images in the directory.

    debug : bool, optional
        Turn on debugging

    output_invalid : bool, optional
        When this option is set, mImgtbl will explicitly output each FITS file
        it finds that does not appear to be valid, along with information on
        the error.

    status_file : str, optional
        Output and errors are written to status_file instead of being written
        to stdout.

    fieldlist : str, optional
        Used to specify a fieldlist, which will list additional keywords to be
        read from the FITS headers and included in the output table.
        Fieldlists should specify the keyword name, type (int,char,double),
        and size.

    img_list : str, optional
        mImgtbl will only process files with names specified in table
        img_list, ignoring any other files in the directory.
    '''
    command = "mImgtbl"
    if recursive:
        command += " -r"
    if corners:
        command += " -c"
    if include_area:
        command += " -a"
    if debug:
        command += " -d"
    if output_invalid:
        command += " -b"
    if status_file:
        command += " -s %s" % str(status_file)
    if fieldlist:
        command += " -f %s" % str(fieldlist)
    if img_list:
        command += " -t %s" % str(img_list)
    command += " " + str(directory)
    command += " " + str(images_table)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mImgtbl", p.stdout.read().strip())


def mMakeHdr(images_table, template_header, debug_level=None,
          status_file=None, cdelt=None, north_aligned=False, system=None,
          equinox=None):
    '''
    From a list of images to be mosaicked together, mMakeHdr generates the
    FITS header that best describes the output image.

    Parameters
    ----------

    images_table : str
        Metadata table (generated by mImgtbl) describing the images to be
        mosaicked.

    template_header : str
        Path to header template to be generated.

    debug_level : int, optional
        Turns on debugging to the specified level (1-3).

    status_file : str, optional
        Output and errors are written to status_file instead of to stdout.

    cdelt : float, optional
        Specify a pixel scale for the header, if different from the input
        images

    north_aligned : bool, optional
        "North-aligned" option. By default, the FITS header generated
        represents the best fit to the images, often resulting in a slight
        rotation. If you want north to be straight up in your final mosaic,
        you should use this option.

    system : str, optional
        Specifies the system for the header (default is Equatorial). Possible
        values are: EQUJ EQUB ECLJ ECLB GAL SGAL

    equinox : str, optional
        If a coordinate system is specified, the equinox can also be given in
        the form YYYY. Default is J2000.
    '''
    command = "mMakeHdr"
    if debug_level:
        command += " -d %s" % str(debug_level)
    if status_file:
        command += " -s %s" % str(status_file)
    if cdelt:
        command += " -p %s" % str(cdelt)
    if north_aligned:
        command += " -n"
    command += " " + str(images_table)
    command += " " + str(template_header)
    if system:
        command += " %s" % str(system)
        if equinox:
            command += " %s" % str(equinox)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mMakeHdr", p.stdout.read().strip())


def mOverlaps(images_table, diffs_table, exact=False, debug_level=None,
          status_file=None):
    '''
    Analyze an image metadata table to determine a list of overlapping images.
    Each image is compared with every other image to determine all overlapping
    image pairs.  A pair of images are deemed to overlap if any pixel around
    the perimeter of one image falls within the boundary of the other image.

    Parameters
    ----------

    images_table : str
        Table of image metadata generated by mImgtbl.

    diffs_table : str
        Path of output table to be generated containing overlap information.

    exact : bool, optional
        Enables 'exact' overlaps mode, as opposed to the default approximate
        algorithm. The default mode uses great-circle connecting lines between
        image corners to determine which images overlap. Exact mode will
        instead check the edge pixels of every image to determine which pixels
        are inside the others. Although the default mode will occasionally
        report some incorrect overlaps, this is not a concern since mDiff will
        detect and ignore these false positive results when processing the
        table.

    debug_level : int, optional
        Turns on debugging to the specified level (1 or 2)

    status_file : str, optional
        Output and errors are sent to status_file instead of to stdout
    '''
    command = "mOverlaps"
    if exact:
        command += " -e"
    if debug_level:
        command += " -d %s" % str(debug_level)
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(images_table)
    command += " " + str(diffs_table)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mOverlaps", p.stdout.read().strip())


def mPix2Coord(template_header, ixpix, jypix, debug=False):
    '''
    Takes an image FITS header template and a pixel (x,y) coordinate, and
    outputs the corresponding sky location.

    Parameters
    ----------

    template_header : str
        ASCII header template describing the image (either a FITS image, or a
        JPEG file created from the FITS file)

    ixpix : int
        X coordinate (pixel location) on image

    jypix : int
        Y coordinate (pixel location) on image

    debug : bool, optional
        Print out additional debugging information
    '''
    command = "mPix2Coord"
    if debug:
        command += " -d"
    command += " " + str(template_header)
    command += " " + str(ixpix)
    command += " " + str(jypix)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mPix2Coord", p.stdout.read().strip())


def mProject(in_image, out_image, template_header, factor=None,
          debug_level=None, status_file=None, hdu=None, scale=None,
          weight_file=None, threshold=None, whole=False):
    '''
    mProject reprojects a single image to the scale defined in a FITS header
    template file (read more about header templates here). The program
    produces a pair of images: the reprojected image and an "area" image
    consisting of the fraction input pixel sky area that went into each output
    pixel.  The "drizzle" algorithm is implemented.  The algorithm proceeds by
    mapping pixel corners (as adjusted by drizzle, if called) from the input
    pixel space to the output pixel space, calculating overlap area with each
    output pixel, and accumulating an appropriate fraction of the input flux
    into the output image pixels.  In addition, the appropriate fraction of
    the input pixel area is accumulated into the area image pixels.
    Projection of points from input pixel space to output pixel space is
    calculated in two steps: first map from input pixel space to sky
    coordinates; second map from sky coordinates to output pixel space.

    Parameters
    ----------

    in_image : str
        Input FITS file to be reprojected.

    out_image : str
        Path of output FITS file to be created.

    template_header : str
        FITS header template to be used in generation of output image

    factor : float, optional
        Processing is done utilizing the drizzle algorithm. factor is a
        floating point number; recommended drizzle factors are from 0.5 to 1.

    debug_level : int, optional
        Causes additional debugging information to be printed to stdout. Valid
        levels are 1-5 (for higher debugging levels, it is recommended to
        redirect the output to a file).

    status_file : str, optional
        Output and errors are written to status_file instead of being written
        to stdout.

    hdu : int, optional
        Use the specified FITS extension (default is to use the first HDU with
        image data)

    scale : float, optional
        Apply a correction factor of scale to each pixel

    weight_file : str, optional
        Path to a weight map to be used when reading values from the input
        image.

    threshold : float, optional
        Pixels with weights below threshold will be treated as blank.

    whole : bool, optional
        Makes the output region (originally defined in the header template)
        big enough to include all of the input images
    '''
    command = "mProject"
    if factor:
        command += " -z %s" % str(factor)
    if debug_level:
        command += " -d %s" % str(debug_level)
    if status_file:
        command += " -s %s" % str(status_file)
    if hdu:
        command += " -h %s" % str(hdu)
    if scale:
        command += " -x %s" % str(scale)
    if weight_file:
        command += " -w %s" % str(weight_file)
    if threshold:
        command += " -t %s" % str(threshold)
    if whole:
        command += " -X"
    command += " " + str(in_image)
    command += " " + str(out_image)
    command += " " + str(template_header)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mProject", p.stdout.read().strip())


def mProjectPP(in_image, out_image, template_header, factor=None,
          debug_level=None, border=None, status_file=None,
          alternate_header=None, hdu=None, scale=None, weight_file=None,
          threshold=None, whole=False):
    '''
    mProjectPP reprojects a single image to the scale defined in an alternate
    FITS header template generated (usually) by mTANhdr. The program produces
    a pair of images: the reprojected image and an "area" image consisting of
    the fraction input pixel sky area that went into each output pixel.  This
    area image goes through all the subsequent processing that the reprojected
    image does, allowing it to be properly coadded at the end.

    Parameters
    ----------

    in_image : str
        Input FITS file to be reprojected.

    out_image : str
        Path to output FITS file to be created.

    template_header : str
        FITS header template to be used in generation of output FITS

    factor : float, optional
        Processing is done utilizing the drizzle algorithm. factor is a
        floating point number; recommended drizzle factors are from 0.5 to 1.

    debug_level : int, optional
        Causes additional debugging information to be printed to stdout. Valid
        levels are 1-5; for levels greater than 1, it's recommended to
        redirect the output into a text file.

    border : int, optional
        Ignores border pixels around the image edge when performing
        calculations.

    status_file : str, optional
        Output and errors are written to status_file instead of being written
        to stdout.

    alternate_header : str, optional
        Specifies an alternate FITS header for use in mProjectPP calculations,
        allows substitution of psuedo-TAN headers created by mTANHdr.

    hdu : int, optional
        Specify the FITS extension to re-project if the FITS image is multi-
        extension.

    scale : float, optional
        Multiple the pixel values by scale when reprojecting. For instance,
        each 2MASS image has a different scale factor (very near 1.0) to
        correct for varying magnitude-zero points.

    weight_file : str, optional
        Path to a weight map to be used when reading values from the input
        image.

    threshold : float, optional
        If using a weight image; only use those pixels where the weight value
        is above threshold.

    whole : bool, optional
        Reproject the whole image even if part of it is outside the region of
        interest (don't crop while re-projecting).
    '''
    command = "mProjectPP"
    if factor:
        command += " -z %s" % str(factor)
    if debug_level:
        command += " -d %s" % str(debug_level)
    if border:
        command += " -b %s" % str(border)
    if status_file:
        command += " -s %s" % str(status_file)
    if alternate_header:
        command += " -[i|o] %s" % str(alternate_header)
    if hdu:
        command += " -h %s" % str(hdu)
    if scale:
        command += " -x %s" % str(scale)
    if weight_file:
        command += " -w %s" % str(weight_file)
    if threshold:
        command += " -t %s" % str(threshold)
    if whole:
        command += " -X"
    command += " " + str(in_image)
    command += " " + str(out_image)
    command += " " + str(template_header)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mProjectPP", p.stdout.read().strip())


def mProjExec(images_table, template_header, proj_dir, stats_table,
          raw_dir=None, debug=False, exact=False, whole=False, border=None,
          restart_rec=None, status_file=None, scale_column=None, mpi=False,
          n_proc=8):
    '''
    An executive which runs mProject (or, if possible for the input/output
    projections, mProjectPP) for each image in an image metadata table.

    Parameters
    ----------

    images_table : str
        ASCII table (generated by mImgtbl) containing metadata for all images
        to be reprojected.

    template_header : str
        FITS header template to be used in generation of output FITS.

    proj_dir : str
        Directory in which to create reprojected images.

    stats_table : str
        Name of table for output statistics (time of each reprojection, or
        error messages).

    raw_dir : str, optional
        Specifies the path to the directory containing the images to be
        reprojected. If the -p option is not included, mProjExec looks for the
        images in the current working directory.

    debug : bool, optional
        Turns on debugging

    exact : bool, optional
        Flag indicating output image should exactly match the FITS header
        template, and not crop off blank pixels

    whole : bool, optional
        Force reprojection of whole images, even if they exceed the area of
        the FITS header template

    border : int, optional
        Ignore border width of pixels around edge of images

    restart_rec : str, optional
        Allows restart at record number restart_rec, if mProjExec exits upon
        an error

    status_file : str, optional
        Output and errors are written to status_file instead of being written
        to stdout.

    scale_column : str, optional
        Turn on flux rescaling (e.g. magnitude zero point correction):
        scale_column is the name of a column in images_table which contains
        scale information.

    mpi : bool, optional
        If set to True, will use the MPI-enabled versions of the Montage
        executable.

    n_proc : int, optional
        If mpi is set to True, n_proc is the number of processes to run
        simultaneously (default is 8)
    '''
    if mpi:
        command = _get_mpi_command(executable="mProjExecMPI", n_proc=n_proc)
    else:
        command = "mProjExec"
    if raw_dir:
        command += " -p %s" % str(raw_dir)
    if debug:
        command += " -d"
    if exact:
        command += " -e"
    if whole:
        command += " -X"
    if border:
        command += " -b %s" % str(border)
    if restart_rec:
        command += " -r %s" % str(restart_rec)
    if status_file:
        command += " -s %s" % str(status_file)
    if scale_column:
        command += " -x %s" % str(scale_column)
    command += " " + str(images_table)
    command += " " + str(template_header)
    command += " " + str(proj_dir)
    command += " " + str(stats_table)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mProjExec", p.stdout.read().strip())


def mPutHdr(in_image, out_image, template_header, debug=False,
          status_file=None, hdu=None):
    '''
    Replaces the header of the input file with one supplied by the user.

    Parameters
    ----------

    in_image : str
        Input FITS file.

    out_image : str
        Path to output FITS file (with new header)

    template_header : str
        ASCII header template to write into out_image.

    debug : bool, optional
        Turns on debugging to the specified level (this version only supports
        level "1").

    status_file : str, optional
        Output and errors are sent to status_file instead of to stdout

    hdu : int, optional
        Write to the specified FITS extnension (HDU).
    '''
    command = "mPutHdr"
    if debug:
        command += " -d"
    if status_file:
        command += " -s %s" % str(status_file)
    if hdu:
        command += " -h %s" % str(hdu)
    command += " " + str(in_image)
    command += " " + str(out_image)
    command += " " + str(template_header)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mPutHdr", p.stdout.read().strip())


def mRotate(in_image, out_image, debug_level=None, status_file=None,
          rotation_angle=None, ra=None, dec=None, xsize=None, ysize=None):
    '''
    Rotates a FITS image by an arbitrary angle.  This module is meant for
    quick-look only; it is not flux conserving.

    Parameters
    ----------

    in_image : str
        Input FITS image.

    out_image : str
        Path to output (rotated) FITS image.

    debug_level : int, optional
        Print out additional debugging information (level can be 1-3)

    status_file : str, optional
        Output and errors are written to status_file instead of stdout.

    rotation_angle : float, optional
        Provide an angle (in degrees) to rotate the image.

    ra, dec, xsize : str, optional
        Center location and width (in degrees) of output image - optional. By
        default, entire input image area will be included in output image.

    ysize : float, optional
        Height (in degrees) of output image, if a new center location and
        width are provided. Only used if ra, dec, and xsize are specified.
        Defaults to xsize.
    '''
    command = "mRotate"
    if debug_level:
        command += " -d %s" % str(debug_level)
    if status_file:
        command += " -s %s" % str(status_file)
    if rotation_angle:
        command += " -r %s" % str(rotation_angle)
    command += " " + str(in_image)
    command += " " + str(out_image)
    if ra and dec and xsize:
        command += " %s" % str(ra)
        command += " %s" % str(dec)
        command += " %s" % str(xsize)
        if ysize:
            command += " %s" % str(ysize)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mRotate", p.stdout.read().strip())


def mShrink(in_image, out_image, factor, fixed_size=False, debug_level=None,
          status_file=None):
    '''
    A utility for reducing the size of a FITS file, by averaging blocks of
    pixels.

    Parameters
    ----------

    in_image : str
        Input FITS file

    out_image : str
        Path to output FITS file.

    factor : float
        Size of blocks, in pixels, to average. File size will be reduced by
        1/factor squared. If the fixed_size option is used, factor is the
        desired width of the output image.

    fixed_size : bool, optional
        Fixed-size option - specify output size of image, instead of the size
        of blocks of pixels to be averaged

    debug_level : int, optional
        Turns on debugging to the specified level (1-4).

    status_file : str, optional
        Output and errors are sent to status_file instead of to stdout
    '''
    command = "mShrink"
    if fixed_size:
        command += " -f"
    if debug_level:
        command += " -d %s" % str(debug_level)
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(in_image)
    command += " " + str(out_image)
    command += " " + str(factor)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mShrink", p.stdout.read().strip())


def mSubimage(in_image, out_image, ra, dec, xsize, debug=False,
          all_pixels=False, hdu=None, status_file=None, ysize=None):
    '''
    Creates a subimage (or "cutout") of a FITS file. To use mSubimage in
    'pixel' mode, see mSubimage_pix

    Parameters
    ----------

    in_image : str
        Input FITS file.

    out_image : str
        Path to output FITS file.

    ra : float
        RA of center of output image.

    dec : float
        Declination of center of output image.

    xsize : float
        Width of output image in degrees.

    debug : bool, optional
        Turns on debugging.

    all_pixels : bool, optional
        All pixels - Force retrieval of whole image (useful to extract an
        entire HDU)

    hdu : int, optional
        Operate on the specified FITS header extension (HDU)

    status_file : str, optional
        Output and errors are sent to status_file instead of to stdout

    ysize : float, optional
        Height of output image in degrees (default is equal to xsize.
    '''
    command = "mSubimage"
    if debug:
        command += " -d"
    if all_pixels:
        command += " -a"
    if hdu:
        command += " -h %s" % str(hdu)
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(in_image)
    command += " " + str(out_image)
    command += " " + str(ra)
    command += " " + str(dec)
    command += " " + str(xsize)
    if ysize:
        command += " %s" % str(ysize)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mSubimage", p.stdout.read().strip())


def mSubimage_pix(in_image, out_image, xstartpix, ystartpix, xpixsize,
          debug=False, hdu=None, status_file=None, ypixsize=None):
    '''
    Creates a subimage (or "cutout") of a FITS file ('pixel' mode)

    Parameters
    ----------

    in_image : str
        Input FITS file.

    out_image : str
        Path to output FITS file.

    xstartpix : int
        Pixel along the x-axis where the cutout image will begin

    ystartpix : int
        Pixel along the y-axis where the cutout image will begin

    xpixsize : int
        Width of output image in pixels

    debug : bool, optional
        Turns on debugging.

    hdu : int, optional
        Operate on the specified FITS header extension (HDU)

    status_file : str, optional
        Output and errors are sent to status_file instead of to stdout

    ypixsize : int, optional
        Height of output image in pixels (default is equal to xpix_size
    '''
    command = "mSubimage -p"
    if debug:
        command += " -d"
    if hdu:
        command += " -h %s" % str(hdu)
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(in_image)
    command += " " + str(out_image)
    command += " " + str(xstartpix)
    command += " " + str(ystartpix)
    command += " " + str(xpixsize)
    if ypixsize:
        command += " %s" % str(ypixsize)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mSubimage_pix", p.stdout.read().strip())


def mSubset(images_table, template_header, subset_table, debug_level=None,
          fast_mode=False, status_file=None):
    '''
    Generates a table of images that is a subset of the input table,
    containing only those images that cover the area defined by a given FITS
    header.

    Parameters
    ----------

    images_table : str
        ASCII table (generated by mImgtbl) containing metadata for image
        collection.

    template_header : str
        FITS header template defining the area of interest.

    subset_table : str
        Path to output table, which will contain only those FITS images
        covering the area defined by template_header.

    debug_level : int, optional
        Turns on debugging to the specified level (1-3).

    fast_mode : bool, optional
        Fast mode - input file must include corners (corners option in
        mImgtbl) to utilize this mode.

    status_file : str, optional
        Output and errors are sent to status_file instead of to stdout
    '''
    command = "mSubset"
    if debug_level:
        command += " -d %s" % str(debug_level)
    if fast_mode:
        command += " -f"
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(images_table)
    command += " " + str(template_header)
    command += " " + str(subset_table)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mSubset", p.stdout.read().strip())


def mTANHdr(orig_header, new_header, debug=False, order=None, max_iter=None,
          tolerance=None, status_file=None):
    '''
    Analyzes a template file and determines if there would be an adequate
    equivalent distorted TAN projection, within a specified tolerance, and
    outputs the alternate header. This header can be used in conjunction with
    mProjectPP to produce a TAN plane image. This process is considerably
    faster than projecting with the general purpose tool mProject.

    Parameters
    ----------

    orig_header : str
        Input FITS header

    new_header : str
        Path to output header to be created

    debug : bool, optional
        Print additional debugging information to stdout.

    order : str, optional
        Order of output header polynomial focal plane distortions (default =
        4)

    max_iter : int, optional
        Maximum number of iteration attempts to produce header (default = 50)

    tolerance : float, optional
        Distortion tolerance value for acceptable output (default = 0.01)

    status_file : str, optional
        Output and errors are written to status_file instead of stdout.
    '''
    command = "mTANHdr"
    if debug:
        command += " -d"
    if order:
        command += " -o %s" % str(order)
    if max_iter:
        command += " -i %s" % str(max_iter)
    if tolerance:
        command += " -t %s" % str(tolerance)
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(orig_header)
    command += " " + str(new_header)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mTANHdr", p.stdout.read().strip())


def mTblSort(in_table, column_name, out_table, debug=False):
    '''
    Sorts a table on numeric values.

    Parameters
    ----------

    in_table : str
        Path to input table

    column_name : str
        Name of column to sort on (column must contain numeric values)

    out_table : str
        Path to output table

    debug : bool, optional
        Turns on debugging
    '''
    command = "mTblSort"
    if debug:
        command += " -d"
    command += " " + str(in_table)
    command += " " + str(column_name)
    command += " " + str(out_table)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mTblSort", p.stdout.read().strip())


def mTileHdr(orig_header, new_header, n_x, n_y, ix, iy, debug=False,
          status_file=None, xpad=None, ypad=None):
    '''
    Takes a header template file and creates another which represents one of a
    regular set of tiles covering the original.  The user specifies the tile
    gridding and which tile is desired.

    Parameters
    ----------

    orig_header : str
        ASCII header template from which to derive tiled headers

    new_header : str
        Path to output header

    n_x : int
        Number of tiles in the x-direction

    n_y : int
        Number of tiles in the y-direction

    ix : int
        Integer identifying the x location of the output tile on the grid
        (counting from 0)

    iy : int
        Integer identifying the y location of the output tile on the grid
        (counting from 0)

    debug : bool, optional
        Turns on debugging.

    status_file : str, optional
        Output and errors are sent to status_file instead of to stdout

    xpad : int, optional
        Number of pixels to overlap tiles in the x direction (default is 0)

    ypad : int, optional
        Number of pixels to overlap tiles in the y direction (default is 0).
        Only used if xpad is present.
    '''
    command = "mTileHdr"
    if debug:
        command += " -d"
    if status_file:
        command += " -s %s" % str(status_file)
    command += " " + str(orig_header)
    command += " " + str(new_header)
    command += " " + str(n_x)
    command += " " + str(n_y)
    command += " " + str(ix)
    command += " " + str(iy)
    if xpad:
        command += " %s" % str(xpad)
        if ypad:
            command += " %s" % str(ypad)
    p = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    stderr = p.stderr.read()
    if stderr:
        raise Exception(stderr)
    return status.parse_struct("mTileHdr", p.stdout.read().strip())