summaryrefslogtreecommitdiffstats
path: root/ds9/library/analysis.tcl
blob: 2a9ba78e6dcc5ac45b3b4db4464ede1b04c44d68 (plain)
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
#  Copyright (C) 1999-2018
#  Smithsonian Astrophysical Observatory, Cambridge, MA, USA
#  For conditions of distribution and use, see copyright notice in "copyright"

package provide DS9 1.0

proc AnalysisDef {} {
    global ianalysis
    global panalysis
    global analysis

    global ds9

    set ianalysis(menu,count) 0
    set ianalysis(menu,hmenu,count) 0
    set ianalysis(menu,hmenu) {}
    set ianalysis(bind,count) 0
    set ianalysis(param,count) 0
    set ianalysis(param,seq) 0
    set ianalysis(file) ".$ds9(app).ans"
    set ianalysis(alt) ".$ds9(app).analysis"

    # temp
    set analysis(load,buf) {}
    set analysis(load,fn) {}

    # prefs only
    set panalysis(log) 0
    set panalysis(autoload) 1
    set panalysis(user) {}
    set panalysis(user2) {}
    set panalysis(user3) {}
    set panalysis(user4) {}
}

proc OpenAnalysisMenu {} {
    set fn [OpenFileDialog analysisfbox]
    if {$fn != {}} {
	ProcessAnalysisFile $fn
    }
}

proc ClearAnalysisMenu {} {
    global pds9

    if {$pds9(confirm)} {
	if {[tk_messageBox -type okcancel -icon question -message [msgcat::mc {Clear External Analysis Commands?}]] != {ok}} {
	    return
	}
    }
    ClearAnalysis
}

# Analysis Menu Delete
proc ClearAnalysis {} {
    global ds9
    global ianalysis

    # is something loaded?
    if {$ianalysis(menu,count) == 0} {
	return
    }

    # delete cascade menus
    for {set ii 0} {$ii<$ianalysis(menu,hmenu,count)} {incr ii} {
	destroy [lindex $ianalysis(menu,hmenu) $ii]
    }
    set ianalysis(menu,hmenu) {}
    set ianalysis(menu,hmenu,count) 0

    # clear menu
    $ds9(mb).analysis delete $ds9(menu,size,analysis) end

    for {set ii 0} {$ii<$ianalysis(menu,count)} {incr ii} {
	unset ianalysis(menu,$ii,parent)
	unset ianalysis(menu,$ii,item)
	unset ianalysis(menu,$ii,template)
	unset ianalysis(menu,$ii,cmd)
	unset ianalysis(menu,$ii,inuse)
	unset ianalysis(menu,$ii,var)
    }
    set ianalysis(menu,count) 0

    # clear all bindings, first
    foreach ff $ds9(frames) {
	for {set ii 0} {$ii<$ianalysis(bind,count)} {incr ii} {
	    $ds9(canvas) bind $ff "$ianalysis(bind,$ii,item)" {}
	}
    }

    # clear bindings
    for {set ii 0} {$ii<$ianalysis(bind,count)} {incr ii} {
	unset ianalysis(bind,$ii,item)
	unset ianalysis(bind,$ii,template)
	unset ianalysis(bind,$ii,cmd)
	unset ianalysis(bind,$ii,inuse)
    }
    set ianalysis(bind,count) 0

    # clear params
    for {set ii 0} {$ii<$ianalysis(param,count)} {incr ii} {
	for {set jj 0} {$jj<$ianalysis(param,$ii,count)} {incr jj} {
	    unset ianalysis(param,$ii,$jj,var)
	    unset ianalysis(param,$ii,$jj,type)
	    unset ianalysis(param,$ii,$jj,title)
	    unset ianalysis(param,$ii,$jj,default)
	    unset ianalysis(param,$ii,$jj,last)
	    unset ianalysis(param,$ii,$jj,value)
	    unset ianalysis(param,$ii,$jj,info)
	}
	unset ianalysis(param,$ii,count)
	unset ianalysis(param,$ii)
    }
    set ianalysis(param,count) 0
}

proc InitAnalysisFile {} {
    global ianalysis
    global panalysis
    global ds9

    set done {}

    # autoload
    if {$panalysis(autoload)} {
	foreach dir [list {.} "[GetEnvHome]/bin" {/usr/local/bin} {/opt/local/bin}] {
	    foreach fn [glob -directory $dir -nocomplain "*.ds9"] {
		if {[file exists $fn]} {
		    ProcessAnalysisFile $fn
		    lappend done $fn
		}
	    }
	}
    }

    # default name ds9.ans
    # backward compatible ds9.analysis
    foreach ff {{.} {~}} {
	foreach gg {{} {.}} {
	    foreach ext {{ans} {analysis}} {
		set fn "$ff/$gg$ds9(app).$ext"
		if {[file exists $fn]} {
		    if {[lsearch $done $fn] == -1} {
			ProcessAnalysisFile $fn
			lappend done $fn
		    }
		}
	    }
	}
    }

    # user specified
    foreach ii {{user} {user2} {user3} {user4}} {
	if {[info exists panalysis($ii)]} {
	    set fn $panalysis($ii)
	    if {[file exists $fn]} {
		if {[lsearch $done $fn] == -1} {
		    ProcessAnalysisFile $fn
		    lappend done $fn
		}
	    }
	}
    }

#    UpdateAnalysisMenu
}

proc ProcessAnalysisFile {fn} {
    global env

    # check for simple file
    if {[file exists "$fn"] && 
	[file isfile "$fn"] && 
	![file executable "$fn"] &&
	![file isdirectory "$fn"]} {

	set ch [open $fn r]
	set data [read $ch]
	close $ch

	if {![ProcessAnalysis data]} {
	    Error "[msgcat::mc {Unable to process Analysis file}] $fn"
	    return
	}

	# add directory to path
	set env(PATH) "[file dirname $fn]:$env(PATH)"
    } else {
	Error "[msgcat::mc {Unable to open file}] $fn"
    }
}

proc ProcessAnalysis {varname} {
    upvar $varname var

    global ds9
    global ianalysis

    # simple check for ascii data
    if {![string is ascii $var]} {
	return 0
    }

    set state 1
    set baseparent $ds9(mb).analysis
    set currentparent $baseparent
    set parentstack $baseparent

    $baseparent add separator

    set lines [split $var \n]
    set l [llength $lines]

    for {set ii 0} {$ii<$l} {incr ii} {
	set line [string trim [lindex $lines $ii]]

	# eat empty lines and comments for all except help
	if {$state != 6} {
	    # empty line
	    if {[string length $line] == 0} continue

	    # comments	    
	    if {[string range $line 0 0] == "\#"} continue

	    # strip any end of line comments
	    set id [string first "\#" $line]
	    if {$id > 0} {
		set line [string range $line 0 [expr $id-1]]
	    }
	}

	switch -- $state {
	    1 {
		# param
		if {[lindex $line 0] == {param}} {
		    if {[lindex $line 1] != {}} {
			set ianalysis(param,$ianalysis(param,count)) \
			    [lindex $line 1]
			set ianalysis(param,$ianalysis(param,count),count) 0
			set state 5
		    }
		    continue
		}

		# help
		if {[lindex $line 0] == {help}} {
		    set id [string first " " $line]
		    if {$id > 0} {
			set item [string range $line [expr $id+1] end]
		    } else {
			set item Help
		    }

		    set i $ianalysis(menu,count)
		    set ianalysis(menu,$i,parent) $currentparent
		    set ianalysis(menu,$i,item) $item
		    set ianalysis(menu,$i,template) {*}
		    set ianalysis(menu,$i,cmd) {help}
		    set ianalysis(menu,$i,inuse) 0
		    set ianalysis(menu,$i,var) {}
		    $currentparent add command -label $item \
			-command [list AnalysisTask $i menu]

		    set state 6
		    continue
		}

		# hmenu
		if {[lindex $line 0] == {hmenu}} {
		    set id [string first " " $line]
		    if {$id > 0} {
			set item [string range $line [expr $id+1] end]
		    } else {
			set item Tasks
		    }

		    # make the menu label unique
		    set nmenu "$currentparent.hmenu$ianalysis(menu,hmenu,count)"
		    lappend ianalysis(menu,hmenu) $nmenu
		    incr ianalysis(menu,hmenu,count)

		    menu $nmenu
		    $currentparent add cascade -label "$item" -menu $nmenu

		    set currentparent $nmenu
		    lappend parentstack $currentparent
		    continue
		}

		# end hmenu
		if {[lindex $line 0] == {endhmenu} ||
		    [lindex $line 0] == {end}} {
		    set parentstack [lreplace $parentstack end end]
		    set currentparent [lindex $parentstack end]
		    continue
		}

		if {[lindex $line 0] == {---}} {
		    $currentparent add separator
		    continue
		}

		# assume new command

		set item "$line"
		set template {}
		set type {}
		set cmd {}
		set state 2
	    }

	    2 {
		set template "$line"
		set state 3
	    }

	    3 {
		set type "$line"
		set state 4
	    }

	    4 {
		set cmd "$line"
		if {$item != {} && $template != {} && 
		    $type != {} && $cmd != {}} {
		    switch -- [lindex $type 0] {
			bind {
			    set b [lindex $type 1]
			    if {$b != {}} {
				set i $ianalysis(bind,count)
				set ianalysis(bind,$i,item) "<$b>"
				set ianalysis(bind,$i,template) "$template"
				set ianalysis(bind,$i,cmd) "$cmd"
				set ianalysis(bind,$i,inuse) 0
				incr ianalysis(bind,count)
			    }
			}
			web {
			    set i $ianalysis(menu,count)
			    set ianalysis(menu,$i,parent) $currentparent
			    set ianalysis(menu,$i,item) $item
			    set ianalysis(menu,$i,template) "$template"
			    set ianalysis(menu,$i,cmd) {web}
			    set ianalysis(menu,$i,inuse) 0
			    set ianalysis(menu,$i,var) "$cmd"
			    $currentparent add command -label "$item" \
				-command [list AnalysisTask $i menu]
			    incr ianalysis(menu,count)
			}
			menu {
			    set i $ianalysis(menu,count)
			    set ianalysis(menu,$i,parent) $currentparent
			    set ianalysis(menu,$i,item) "$item"
			    set ianalysis(menu,$i,template) "$template"
			    set ianalysis(menu,$i,cmd) "$cmd"
			    set ianalysis(menu,$i,inuse) 0
			    set ianalysis(menu,$i,var) {}
			    $currentparent add check -label "$item" \
				-command [list AnalysisTask $i menu] \
				-variable ianalysis(menu,$i,inuse) \
				-selectcolor green
			    incr ianalysis(menu,count)
			}
			default {
			    # something really wrong here, abort
			    return 0
			}
		    }
		}
		set state 1
	    }

	    5 {
		# end param
		if {[lindex $line 0] == {endparam} || 
		    [lindex $line 0] == {end}} {
		    incr ianalysis(param,count)
		    set state 1
		    continue
		}

		if {[string range $line 0 0] == {@}} {
		    ParseIRAFParam [string range $line 1 end]
		    continue
		}

		set i $ianalysis(param,count)
		set j $ianalysis(param,$i,count)
		set ianalysis(param,$i,$j,var) [lindex $line 0]
		set ianalysis(param,$i,$j,type) [lindex $line 1]
		set ianalysis(param,$i,$j,title) [lindex $line 2]

		# default can contain the full menu 'aaa|bbb|ccc'
		set ianalysis(param,$i,$j,default) [lindex $line 3]
		# set last to first item
		set ianalysis(param,$i,$j,last) \
		    [lindex [split [lindex $line 3] |] 0]
		# and set value to last
		set ianalysis(param,$i,$j,value) \
		    $ianalysis(param,$i,$j,last)

		set ianalysis(param,$i,$j,info) [lindex $line 4]
		incr ianalysis(param,$i,count)
	    }

	    6 {
		# end help
		if {[lindex $line 0] == {endhelp} ||
		    [lindex $line 0] == {end}} {
		    incr ianalysis(menu,count)
		    set state 1
		    continue
		}

		set i $ianalysis(menu,count)
		append ianalysis(menu,$i,var) "$line\n"
	    }
	}
    }

    # events
    UnBindEventsCanvas
    BindEventsCanvas

    UpdateAnalysisMenu

    return 1
}

proc AnalysisTask {i which {frame {}} {x 0} {y 0} {sync 0}} {
    global ianalysis
    global current

    if {$frame == {}} {
	set frame $current(frame)
    }

    switch -- $ianalysis($which,$i,cmd) {
	help {
	    AnalysisText "at${which}${i}" $ianalysis($which,$i,item) \
		$ianalysis($which,$i,var) insert
	}
	web {
	    if {$frame != {}} {
		AnalysisWebDoit $i $which $frame $x $y $sync
	    }
	}
	default {
	    if {$frame != {}} {
		AnalysisTaskDoit $i $which $frame $x $y $sync
	    }
	}
    }
}

proc AnalysisWebDoit {i which frame x y sync} {
    global ianalysis
    global panalysis

    set cmd "$ianalysis($which,$i,var)"

    # do select macro expansion

    # escaped macros
    SetEscapedMacros cmd

    # $xpa_method
    ParseXPAMethodMacro cmd

    # $xpa
    ParseXPAMacro cmd

    # $vo_method
    ParseVOMethodMacro cmd

    # $xdim,$ydim,$bitpix
    ParseXYBitpixMacro cmd $frame

    # $filename[$regions]
    ParseFilenameRegionMacro cmd $frame

    # $filename
    ParseFilenameMacro cmd $frame

    # $filedialog
    ParseFileDialogMacro cmd

    # $regions
    ParseRegionMacro cmd $frame

    # $env
    ParseEnvMacro cmd

    # $pan
    ParsePanMacro cmd $frame

    # $value
    ParseValueMacro cmd $frame $x $y

    # $x,$y
    ParseXYMacro cmd $frame $x $y

    # $z
    ParseZMacro cmd $frame

    # escaped macros
    UnsetEscapedMacros cmd

    if {$panalysis(log)} {
	SimpleTextDialog acmd [msgcat::mc {Analysis Commands}] \
	    80 20 append bottom "$cmd\n"
    }

    HVAnalysisCmd "at${which}${i}" "$ianalysis($which,$i,item)" "$cmd" $sync
}

proc AnalysisTaskDoit {i which frame x y sync} {
    global ianalysis
    global pds9

    if {[info exists ianalysis($which,$i,pid)]} {
	set ianalysis($which,$i,inuse) 1

	if {$pds9(confirm)} {
	    if {[tk_messageBox -type okcancel -icon question -message [msgcat::mc {This analysis task is already running. Do you wish to kill it?}]] != {ok}} {
		return
	    }
	}

	if {[info exists ianalysis($which,$i,pid)]} {
	    if {$ianalysis($which,$i,pid)>0} {
		eval "exec kill -9 $ianalysis($which,$i,pid)"
	    } else {
		HVAnalysisCancel $which $i
	    }
	}

	return
    }

    # don't turn on til task has started
    set ianalysis($which,$i,inuse) 0

    set ianalysis($which,$i,start) {}
    set ianalysis($which,$i,start,fn) {}
    set ianalysis($which,$i,start,url) {}
    set ianalysis($which,$i,finish) {}
    set ianalysis($which,$i,result) {}
    set ianalysis($which,$i,plot,title) {}
    set ianalysis($which,$i,plot,xaxis) {}
    set ianalysis($which,$i,plot,yaxis) {}
    set ianalysis($which,$i,plot,dim) 2
    set ianalysis($which,$i,image) {}

    set cmd $ianalysis($which,$i,cmd)

    # escaped macros
    SetEscapedMacros cmd

    # $data
    ParseDataMacro cmd $which $i

    # $xpa_method
    ParseXPAMethodMacro cmd

    # $xpa
    ParseXPAMacro cmd

    # $vo_method
    ParseVOMethodMacro cmd

    # $xdim,$ydim,$bitpix
    ParseXYBitpixMacro cmd $frame

    # $filename[$regions]
    ParseFilenameRegionMacro cmd $frame

    # $filename
    ParseFilenameMacro cmd $frame

    # $filedialog
    ParseFileDialogMacro cmd

    # $regions
    ParseRegionMacro cmd $frame

    # $env
    ParseEnvMacro cmd

    # $cen
    ParsePanMacro cmd $frame

    # $value
    ParseValueMacro cmd $frame $x $y

    # $x,$y
    ParseXYMacro cmd $frame $x $y

    # $z
    ParseZMacro cmd $frame

    # $message
    if {![ParseMessageMacro cmd]} {
	AnalysisTaskEnd $which $i
	return
    }

    # $entry
    if {![ParseEntryMacro cmd]} {
	AnalysisTaskEnd $which $i
	return
    }

    # $param
    if {![ParseParamMacro cmd]} {
	AnalysisTaskEnd $which $i
	return
    }

    # $text
    ParseTextMacro cmd $which $i

    # $plot
    ParsePlotMacro cmd $which $i

    # $null
    ParseNullMacro cmd $which $i

    # $url
    ParseURLMacro cmd $which $i

    # $geturl
    # do this next to last
    ParseGetURLMacro cmd $which $i

    # $image
    # do this last
    ParseImageMacro cmd $which $i

    # escaped macros
    UnsetEscapedMacros cmd

    # ok, we are off and running
    set ianalysis($which,$i,inuse) 1

    switch -- $ianalysis($which,$i,start) {
	geturl {
	    AnalysisGetURL $which $i $sync
	}
	default {
	    AnalysisPipe $which $i $cmd $sync
	}
    }
}

proc AnalysisPipe {which i cmd sync} {
    global ianalysis
    global panalysis
    global current

    switch -- $ianalysis($which,$i,start) {
	data {$current(frame) save fits image file "\{$ianalysis($which,$i,start,fn)\}"}
	url {GetFileURL $ianalysis($which,$i,start,url) ianalysis($which,$i,start,fn)}
    }

    # last step, change all '][' into ',' so that multiple filters work right
    regsub -all {\]\[} $cmd "," cmd

    # log the command, if necessary
    if {$panalysis(log)} {
	SimpleTextDialog acmd [msgcat::mc {Analysis Commands}] \
	    80 20 append bottom "$cmd\n"
    }

    switch -- $ianalysis($which,$i,finish) {
	null {
	    # nothing is returned, so there is aways an error,
	    # however, the command will be executed.
	    catch {open "| $cmd"}
	    global errorInfo
	    set errorInfo {}
	    AnalysisTaskEnd $which $i
	    return
	}
	default {
	    if {[catch {set ch [open "| $cmd"]}]} {
		Error [msgcat::mc {An error has occurred invoking the Analysis task}]
		AnalysisTaskEnd $which $i
		return
	    }
	    set ianalysis($which,$i,pid) [pid $ch]

	    switch -- $ianalysis($which,$i,finish) {
		image {
		    switch -- $ianalysis($which,$i,image) {
			new {CreateFrame}
			rgb {CreateRGBFrame}
			3d {Create3DFrame}
			current {}
		    }
		    global loadParam
		    set loadParam(load,type) channel
		    set loadParam(load,layer) {}
		    set loadParam(channel,name) $ch
		    set loadParam(file,type) fits
		    set loadParam(file,mode) {}
		    set loadParam(file,name) \
			"[string tolower [lindex $ianalysis($which,$i,item) 0]].fits"

		    ProcessLoad
		    FinishLoad

		    AnalysisTaskEnd $which $i
		}
		default {
		    if {$sync} {
			AnalysisReaderAppend $ch $which $i
			AnalysisReaderFinish $ch $which $i
		    } else {
			fileevent $ch readable \
			    [list AnalysisReader $ch $which $i]
			fconfigure $ch -blocking 0 -buffering none
		    }
		}
	    }
	}
    }
}

proc AnalysisReader {ch which i} {
    global ianalysis

    if {[eof $ch]} {
	AnalysisReaderFinish $ch $which $i
	return
    }
    AnalysisReaderAppend $ch $which $i
}

proc AnalysisReaderAppend {ch which i} {
    global ianalysis

    set r [read $ch]
    # for real-time update
    switch -- $ianalysis($which,$i,finish) {
	text {
	    AnalysisText "at${which}${i}" $ianalysis($which,$i,item) $r append

	    global debug
	    if {$debug(tcl,idletasks)} {
		puts stderr "AnalysisReader"
	    }
	    update idletasks
	}
    }
    append ianalysis($which,$i,result) $r
}

proc AnalysisReaderFinish {ch which i} {
    global ianalysis

    catch {close $ch}

    switch -- $ianalysis($which,$i,finish) {
	null -
	image -
	text {}
	plot {
	    PlotLine "at${which}${i}" \
		$ianalysis($which,$i,item) \
		$ianalysis($which,$i,plot,title) \
		$ianalysis($which,$i,plot,xaxis) \
		$ianalysis($which,$i,plot,yaxis) \
		$ianalysis($which,$i,plot,dim) \
		$ianalysis($which,$i,result)
	}
	plotstdin {
	    AnalysisPlotStdin line "at${which}${i}" $ianalysis($which,$i,item) \
		$ianalysis($which,$i,result)
	}
	default {puts stdout $ianalysis($which,$i,result)}
    }

    AnalysisTaskEnd $which $i
}

proc AnalysisPlotStdin {type w wtt result} {
    # if no result, just return
    if {$result == {}} {
	return
    }

    # check for $ERROR
    set id [string first {$ERROR} $result]
    if {$id >= 0} {
	AnalysisText "${w}e" $wtt \
	    [string range $result [expr $id+1] end] append
	return
    }

    # check for ERROR:
    set id [string first {ERROR:} $result]
    if {$id >= 0} {
	AnalysisText "${w}e" $wtt [string range $result $id end] append
	return
    }

    # check for $BEGINTEXT/$ENDTEXT
    # assume each is followed by a \n, so skip it
    if {[string range $result 0 9] == {$BEGINTEXT}} {
	set eid [string first {$ENDTEXT} $result]
	if {$eid > 0} {
	    AnalysisText "${w}t" $wtt \
		[string range $result 11 [expr $eid-1]] append
	    set result [string range $result [expr $eid+9] end]
	} else {
	    # looks like all text
	    AnalysisText "${w}t" $wtt [string range $result 11 end] append
	    return
	}
    }    

    # now find the title, x axis label, y axis label, and dimension
    set id [string first "\n" $result]
    set tt [string range $result 0 $id]
    set rr [string range $result [expr $id+1] end]

    set l [llength $tt]
    set t [join [lrange $tt 0 [expr $l-4]]]
    set x [lindex $tt [expr $l-3]]
    set y [lindex $tt [expr $l-2]]
    set d [lindex $tt [expr $l-1]]

    if {$d != {} && $rr != {}} {
	switch $type {
	    line {PlotLine $w $wtt $t $x $y $d $rr}
	    bar {PlotBar $w $wtt $t $x $y $d $rr}
	    scatter {PlotScatter $w $wtt $t $x $y $d $rr}
	}
    } else {
	Error "[msgcat::mc {Error}] [string range $tt 0 40]"
    }
}

proc AnalysisGetURL {which i sync} {
    global ianalysis
    global panalysis

    if {![ParseURL $ianalysis($which,$i,start,url) r]} {
	Error [msgcat::mc {An error has occurred invoking the Analysis task}]
	AnalysisTaskEnd $which $i
	return
    }

    # format all spaces and brackets
    set url {}
    regsub -all { } $ianalysis($which,$i,start,url) "%20" url
    regsub -all {\[} $url "%5B" url
    regsub -all {\]} $url "%5D" url

    if {$panalysis(log)} {
	SimpleTextDialog acmd [msgcat::mc {Analysis Commands}] \
	    80 20 append bottom "$url\n"
    }

    set ianalysis($which,$i,pid) -1
    HVAnalysisURL $which $i $url $sync
}

proc AnalysisProcessGetURL {which i result} {
    global ianalysis

    set ianalysis($which,$i,result) $result
    switch -- $ianalysis($which,$i,finish) {
	text {AnalysisText "at${which}${i}" $ianalysis($which,$i,item) \
		  $ianalysis($which,$i,result) append}
	plot {PlotLine "at${which}${i}" \
		  $ianalysis($which,$i,item) \
		  $ianalysis($which,$i,plot,title) \
		  $ianalysis($which,$i,plot,xaxis) \
		  $ianalysis($which,$i,plot,yaxis) \
		  $ianalysis($which,$i,plot,dim) \
		  $ianalysis($which,$i,result)}
	plotstdin {AnalysisPlotStdin line "at${which}${i}" \
		       $ianalysis($which,$i,item) \
		       $ianalysis($which,$i,result)}
	image {
	    set fn "[string tolower [lindex $ianalysis($which,$i,item) 0]].fits"
	    LoadVar result $fn {} {}
	}
	default {Error $ianalysis($which,$i,result)}
    }
}

proc AnalysisTaskEnd {which i} {
    global ianalysis

    set ianalysis($which,$i,inuse) 0
    if {$ianalysis($which,$i,start,fn) != {}} {
	if {[file exists $ianalysis($which,$i,start,fn)]} {
	    catch {file delete -force $ianalysis($which,$i,start,fn)}
	}
    }

    if {[info exists ianalysis($which,$i,pid)]} {
	unset ianalysis($which,$i,pid)
    }
    unset ianalysis($which,$i,start)
    unset ianalysis($which,$i,start,fn)
    unset ianalysis($which,$i,start,url)
    unset ianalysis($which,$i,finish)
    unset ianalysis($which,$i,result)
    unset ianalysis($which,$i,plot,title)
    unset ianalysis($which,$i,plot,xaxis)
    unset ianalysis($which,$i,plot,yaxis)
    unset ianalysis($which,$i,plot,dim)
    unset ianalysis($which,$i,image)
}

proc SetEscapedMacros {cmdname} {
    upvar $cmdname cmd
    global xpa

    set seq "WaJaWaJaW"
    if {[regexp {\$\$} $cmd]} {
	# fill with tempory sequence
	regsub -all {\$\$} $cmd $seq cmd
    }
}

proc UnsetEscapedMacros {cmdname} {
    upvar $cmdname cmd
    global xpa

    set seq "WaJaWaJaW"
    if {[regexp $seq $cmd]} {
	# reset to $
	regsub -all $seq $cmd {\$} cmd
    }
}

proc ParseDataMacro {cmdname which i} {
    upvar $cmdname cmd
    global ianalysis

    set exp {\$data.?\|}
    if {[regexp $exp $cmd]} {
	set ianalysis($which,$i,start) data
	set ianalysis($which,$i,start,fn) [tmpnam {.fits}]

	regsub $exp $cmd "cat \{$ianalysis($which,$i,start,fn)\} |" cmd
    }
}

proc ParseVOMethodMacro {cmdname} {
    upvar $cmdname cmd
    global pvo

    if {[regexp {\$vo_method} $cmd]} {
	regsub -all {\$vo_method} $cmd $pvo(method) cmd
    }
}

proc ParseXPAMethodMacro {cmdname} {
    upvar $cmdname cmd
    global ds9

    if {[regexp {\$xpa_method} $cmd]} {
	regsub -all {\$xpa_method} $cmd [XPAMethod] cmd
    }
}

proc ParseXPAMacro {cmdname} {
    upvar $cmdname cmd
    global ds9

    if {[regexp {\$xpa} $cmd]} {
	regsub -all {\$xpa} $cmd $ds9(title) cmd
    }
}

proc ParseXYBitpixMacro {cmdname frame} {
    upvar $cmdname cmd

    if {$frame != {}} {
	if {[regexp {\$width} $cmd]} {
	    regsub -all {\$width} $cmd [$frame get fits width] cmd
	}

	if {[regexp {\$height} $cmd]} {
	    regsub -all {\$height} $cmd [$frame get fits height] cmd
	}

	if {[regexp {\$depth} $cmd]} {
	    regsub -all {\$depth} $cmd [$frame get fits depth 2] cmd
	}

	if {[regexp {\$bitpix} $cmd]} {
	    regsub -all {\$bitpix} $cmd [$frame get fits bitpix] cmd
	}

	if {[regexp {\$xdim} $cmd]} {
	    regsub -all {\$xdim} $cmd [$frame get fits width] cmd
	}

	if {[regexp {\$ydim} $cmd]} {
	    regsub -all {\$ydim} $cmd [$frame get fits height] cmd
	}
    }
}

proc ParseFilenameRegionMacro {cmdname frame} {
    upvar $cmdname cmd

    set exp {(\$filename)\[(\$regions\(([^)]*)\))\]}
    while {[regexp $exp $cmd foo fn reg pp]} {
	set type ds9
	set prop {}
	set sys physical
	set sky fk5
	set format degrees

	# default for mosaics
	if {$frame != {}} {
	    if {[$frame has fits mosaic]} {
		set sys wcs
	    }
	}

	foreach p [split $pp ,] {
	    switch -- $p {
		ds9 -
		ciao -
		saotng -
		saoimage -
		pros -
		xy {set type $p}

		include {append prop {include = yes }}
		exclude {append prop {include = no }}
		source {append prop {source = yes }}
		background {append prop {source = no }}

		image -
		physical -
		detector -
		amplifier
		wcs -
		wcsa -
		wcsb -
		wcsc -
		wcsd -
		wcse -
		wcsf -
		wcsg -
		wcsh -
		wcsi -
		wcsj -
		wcsk -
		wcsl -
		wcsm -
		wcsn -
		wcso -
		wcsp -
		wcsq -
		wcsr -
		wcss -
		wcst -
		wcsu -
		wcsv -
		wcsw -
		wcsx -
		wcsy -
		wcsz {set sys $p}

		fk4 -
		b1950 -
		fk5 -
		j2000 -
		icrs -
		galactic -
		ecliptic {
		    if {"$sys"=="physical"} {
			set sys wcs
		    }
		    set sky $p
		}

		hms {set format sexagesimal}
		sexagesimal -
		degrees {set format $p}
	    }
	}

	SubstFilenameRegion cmd $frame $exp $type $prop $sys $sky $format
    }

    set exp {(\$filename)\[(\$regions)\]}
    while {[regexp $exp $cmd foo fn reg]} {
	set type ds9
	set prop {}
	set sys physical
	set sky fk5
	set format degrees

	# default for mosaics
	if {$frame != {}} {
	    if {[$frame has fits mosaic]} {
		set sys wcs
	    }
	}

	SubstFilenameRegion cmd $frame $exp $type $prop $sys $sky $format
    }
}

proc SubstFilenameRegion {cmdname frame exp type prop sys sky format} {
    upvar $cmdname cmd
    global ianalysis

    set fn [$frame get fits file name full]
    set region [string trimright [$frame marker list $type $sys $sky $format yes $prop] ";"]
    
    if {$region != {}} {
	set sub {}
	foreach f $fn {
	    append sub "$f\[$region\] "
	}
    } else {
	set sub $fn
    }

    # substitute
    # ok, we need to check the length
    if {[string length $region] > 256} {
	# since we are writing to a file, 
	# we don't have to worry about quoting
	# special characters
	set fn [tmpnam {.reg}]
	incr ianalysis(param,seq)

	if {![catch {set ch [open "$fn" w]}]} {
	    puts $ch "$sub"
	    close $ch
	}

	regsub $exp $cmd "\@$fn" cmd

    } else {
	CleanFileName sub
        regsub $exp $cmd $sub cmd
    }
}

proc ParseFilenameMacro {cmdname frame} {
    upvar $cmdname cmd

    set exp {\$filename\(([^)]*)\)}
    if {[regexp $exp $cmd foo pp]} {
	switch $pp {
	    root -
	    root,base {
		set sub [join [$frame get fits file name root base]]
		CleanFileName sub
		regsub -all $exp $cmd $sub cmd
	    }
	    full -
	    full,base {
		set sub [join [$frame get fits file name full base]]
		CleanFileName sub
		regsub -all $exp $cmd $sub cmd
	    }
	}
    }

    set exp {\$filename}
    if {[regexp $exp $cmd]} {
	set sub [join [$frame get fits file name full]]
	CleanFileName sub
	regsub -all $exp $cmd $sub cmd
    }
}

proc ParseFileDialogMacro {cmdname} {
    upvar $cmdname cmd

    set exp {\$filedialog\(open\)}
    if {[regexp $exp $cmd]} {
	set sub [OpenFileDialog analysisparamfbox]
	regsub -all $exp $cmd $sub cmd
    }

    set exp {\$filedialog\(save\)}
    if {[regexp $exp $cmd]} {
	set sub [SaveFileDialog analysisparamfbox]
	regsub -all $exp $cmd $sub cmd
    }
}

proc CleanFileName {varname} {
    upvar $varname sub

    # we have to quote {"}, else problems down the road
    regsub -all {\"} $sub {\\"} sub

    # we have to quote {&}, else problems down the road
    regsub -all {\&} $sub {\\&} sub
}

proc ParseRegionMacro {cmdname frame} {
    upvar $cmdname cmd

    set exp {\$regions\(([^)]*)\)}
while {[regexp $exp $cmd foo pp]} {

    set type ds9
    set prop {}
    set sys physical
    set sky fk5
    set format degrees

    # default for mosaics
    if {$frame != {}} {
	if {[$frame has fits mosaic]} {
	    set sys wcs
	}
    }

    foreach p [split $pp ,] {
	switch -- $p {
	    ds9 -
	    ciao -
	    saotng -
	    saoimage -
	    pros -
	    xy {set type $p}

	    include {append prop {include = yes }}
	    exclude {append prop {include = no }}
	    source {append prop {source = yes }}
	    background {append prop {source = no }}

	    image -
	    physical -
	    detector -
	    amplifier -
	    wcs -
	    wcsa -
	    wcsb -
	    wcsc -
	    wcsd -
	    wcse -
	    wcsf -
	    wcsg -
	    wcsh -
	    wcsi -
	    wcsj -
	    wcsk -
	    wcsl -
	    wcsm -
	    wcsn -
	    wcso -
	    wcsp -
	    wcsq -
	    wcsr -
	    wcss -
	    wcst -
	    wcsu -
	    wcsv -
	    wcsw -
	    wcsx -
	    wcsy -
	    wcsz {set sys $p}

	    fk4 -
	    b1950 -
	    fk5 -
	    j2000 -
	    icrs -
	    galactic -
	    ecliptic {
		if {"$sys"=="physical"} {
		    set sys wcs
		}
		set sky $p
	    }

	    hms {set format sexagesimal}
	    sexagesimal -
	    degrees {set format $p}
	}
    }

    SubstRegion cmd $frame $exp $type $prop $sys $sky $format
}

# SAOtng format
set exp {\$((|include|exclude|source|background)_)?regions(_(|degrees|hms|pixels))?}
while {[regexp  $exp $cmd foo a prop b sys]} {

    # check valid props
    switch -- $prop {
	include {set prop {include = yes}}
	exclude {set prop {include = no}}
	source {set prop {source = yes}}
	background {set prop {source = no}}
	default {set prop {}}
    }

    # check valid coordinate systems
    set sky fk5
    switch -- $sys {
	degrees {set sys wcs; set format degrees}
	hms {set sys wcs; set format sexagesimal}
	pixels -
	default {set sys physical; set format degrees}
    }

    SubstRegion cmd $frame $exp ds9 $prop $sys $sky $format
}
}

proc SubstRegion {cmdname frame exp type prop sys sky format} {
    upvar $cmdname cmd
    global ianalysis

    # get any regions
    set region [string trimright [$frame marker list $type $sys $sky $format yes $prop] ";"]

    # substitute
    # ok, we need to check the length
    if {[string length $region] > 8192} {
	# since we are writing to a file, we don't have to worry about quoting
	# special characters
        set fn [tmpnam {.reg}]
        incr ianalysis(param,seq)

        if {![catch {set ch [open "$fn" w]}]} {
            puts $ch "$region"
            close $ch
        }

        regsub $exp $cmd "\@$fn" cmd

    } else {
        # we have to quote {"}, else problems down the road
        regsub -all {\"} $region {\\"} region

        # we have to quote {&}, else problems down the road
        regsub -all {\&} $region {\\&} region

        regsub $exp $cmd $region cmd
    }
}

proc ParseEnvMacro {cmdname} {
    upvar $cmdname cmd
    global env

    set exp {\$env\(([^)]*)\)}
if {[regexp $exp $cmd foo ee]} {
    if {[info exists env($ee)]} {
	regsub -all $exp $cmd "$env($ee)" cmd
    } else {
	regsub -all $exp $cmd {} cmd
    }
}
}

proc ParsePanMacro {cmdname frame} {
    upvar $cmdname cmd

    set exp {\$pan\(([^)]*)\)}
if {[regexp $exp $cmd foo pp]} {
    set sys physical
    set sky fk5
    set format degrees

    foreach p [split $pp ,] {
	switch -- $p {
	    image -
	    physical -
	    detector -
	    amplifier -
	    wcs -
	    wcsa -
	    wcsb -
	    wcsc -
	    wcsd -
	    wcse -
	    wcsf -
	    wcsg -
	    wcsh -
	    wcsi -
	    wcsj -
	    wcsk -
	    wcsl -
	    wcsm -
	    wcsn -
	    wcso -
	    wcsp -
	    wcsq -
	    wcsr -
	    wcss -
	    wcst -
	    wcsu -
	    wcsv -
	    wcsw -
	    wcsx -
	    wcsy -
	    wcsz {set sys $p}

	    fk4 -
	    b1950 -
	    fk5 -
	    j2000 -
	    icrs -
	    galactic -
	    ecliptic {set sky $p; set sys wcs}

	    hms {set format sexagesimal}
	    sexagesimal -
	    degrees {set format $p}
	}
    }
    
    set coord [$frame get cursor $sys $sky $format]
    regsub -all $exp $cmd "[lindex $coord 0],[lindex $coord 1]" cmd

    return
}

# no args

set exp {\$pan}
if {[regexp $exp $cmd foo1]} {
    set coord [$frame get cursor physical]
    regsub -all $exp $cmd "[lindex $coord 0],[lindex $coord 1]" cmd
}
}

proc ParseValueMacro {cmdname frame x y} {
    upvar $cmdname cmd

    # menu items will not have a frame arg
    if {$frame == {}} {
	return
    }

    set exp1 {\$value}
    if {[regexp $exp1 $cmd foo]} {
        set vv [$frame get value canvas $x $y]
        regsub -all $exp1 $cmd "$vv" cmd
    }
}

proc ParseXYMacro {cmdname frame x y} {
    upvar $cmdname cmd

    # menu items will not have a frame arg
    if {$frame == {}} {
	return
    }

    set exp1 {\$x\(([^)]*)\)}
set exp2 {\$y\(([^)]*)\)}
if {[regexp $exp1 $cmd foo pp] && [regexp $exp2 $cmd foo2 pp2]} {
    set sys physical
    set sky fk5
    set format degrees

    foreach p [split $pp ,] {
	switch -- $p {
	    image -
	    physical -
	    detector -
	    amplifier -
	    wcs -
	    wcsa -
	    wcsb -
	    wcsc -
	    wcsd -
	    wcse -
	    wcsf -
	    wcsg -
	    wcsh -
	    wcsi -
	    wcsj -
	    wcsk -
	    wcsl -
	    wcsm -
	    wcsn -
	    wcso -
	    wcsp -
	    wcsq -
	    wcsr -
	    wcss -
	    wcst -
	    wcsu -
	    wcsv -
	    wcsw -
	    wcsx -
	    wcsy -
	    wcsz {set sys $p}

	    fk4 -
	    b1950 -
	    fk5 -
	    j2000 -
	    icrs -
	    galactic -
	    ecliptic {set sky $p; set sys wcs}

	    hms {set format sexagesimal}
	    sexagesimal -
	    degrees {set format $p}
	}
    }
    
    switch -- $sys {
	image -
	physical -
	detector -
	amplifier {set coord [$frame get coordinates $x $y $sys]}
	default {set coord [$frame get coordinates $x $y $sys $sky $format]}
    }

    regsub -all $exp1 $cmd [lindex $coord 0] cmd
    regsub -all $exp2 $cmd [lindex $coord 1] cmd

    return
}

# no args

set exp1 {\$x}
set exp2 {\$y}
if {[regexp $exp1 $cmd foo1] && [regexp $exp2 $cmd foo2]} {
    set coord [$frame get coordinates $x $y physical]

    regsub -all $exp1 $cmd [lindex $coord 0] cmd
    regsub -all $exp2 $cmd [lindex $coord 1] cmd
}
}

proc ParseZMacro {cmdname frame} {
    upvar $cmdname cmd

    # menu items will not have a frame arg
    if {$frame == {}} {
	return
    }

    set sl [$frame get fits slice]

    # args
    set exp1 {\$z\(([^)]*)\)}
    if {[regexp $exp1 $cmd foo pp]} {
        set sys $pp
        set coord [$frame get coordinates $sl image $sys 2]
        regsub -all $exp1 $cmd "$coord" cmd
        return
    }

    # no args
    # look for '$z"'
    set exp1 {\$z\"}
    if {[regexp $exp1 $cmd foo1]} {
        regsub -all $exp1 $cmd "$sl\"" cmd
    }
    # look for "$z "
    set exp1 {\$z\s}
    if {[regexp $exp1 $cmd foo1]} {
        regsub -all $exp1 $cmd "$sl " cmd
    }
}

proc ParseMessageMacro {cmdname} {
    upvar $cmdname cmd

    # two args
    set exp {\|?.?\$message\((ok|okcancel|yesno),([^)]*)\).?\|?}
while {[regexp $exp $cmd foo type message]} {
    regsub $exp $cmd {} cmd
    if {![AnalysisMessage $type $message]} {
	return 0
    }
}

# one args
set exp {\|?.?\$message\(([^)]*)\).?\|?}
while {[regexp $exp $cmd foo message]} {
    regsub $exp $cmd {} cmd
    AnalysisMessage ok $message
}

return 1
}

proc ParseEntryMacro {cmdname} {
    upvar $cmdname cmd
    
    # one args
    set exp {\|?.?\$entry\(([^)]*)\).?\|?}
while {[regexp $exp $cmd foo message]} {
    set result {}
    if {![AnalysisEntry $message result]} {
	return 0
    }
    regsub $exp $cmd $result cmd
}

return 1
}

proc ParseParamMacro {cmdname} {
    upvar $cmdname cmd
    global ianalysis

    set exp {\$param\(([^)]*)\).?;?}
while {[regexp  $exp $cmd foo param]} {
    regsub $exp $cmd {} cmd
    if {![AnalysisParam cmd $param]} {
	return 0
    }
}
return 1
}

proc ParseTextMacro {cmdname which i} {
    upvar $cmdname cmd
    global ianalysis

    set exp1 {\|.?\$text}
    set exp2 {\|\&.?\$text}
    if {[regexp $exp1 $cmd]} {
	regsub $exp1 $cmd {} cmd

	set ianalysis($which,$i,finish) text
    } elseif {[regexp $exp2 $cmd]} {
	regsub $exp2 $cmd { 2>@ stdout} cmd

	set ianalysis($which,$i,finish) text
    }
}

proc ParseNullMacro {cmdname which i} {
    upvar $cmdname cmd
    global ianalysis

    set exp {\|.?\$null}
    if {[regexp $exp $cmd]} {
	regsub $exp $cmd {} cmd

	set ianalysis($which,$i,finish) null
    }
}

proc ParsePlotMacro {cmdname which i} {
    upvar $cmdname cmd
    global ianalysis

    set exp {\|.?\$plot\(([^,]+),([^,]+),([^,]+),([^)]+)\)}
if {[regexp $exp $cmd foo \
	 ianalysis($which,$i,plot,title) \
	 ianalysis($which,$i,plot,xaxis) \
	 ianalysis($which,$i,plot,yaxis) \
	 ianalysis($which,$i,plot,dim)]} {
    regsub $exp $cmd {} cmd

    set ianalysis($which,$i,finish) plot
}

set exp {\|.?\$plot\(stdin\)}
if {[regexp $exp $cmd]} {
    regsub $exp $cmd {} cmd

    set ianalysis($which,$i,finish) plotstdin
}

set exp {\|.?\$plot}
if {[regexp $exp $cmd]} {
    regsub $exp $cmd {} cmd

    set ianalysis($which,$i,finish) plot
}
}

proc ParseURLMacro {cmdname which i} {
    upvar $cmdname cmd
    global ianalysis

    set exp {\$url\((.*)\) \|}
    if {[regexp $exp $cmd foo ianalysis($which,$i,start,url)]} {
	set ianalysis($which,$i,start) url
	set ianalysis($which,$i,start,fn) [tmpnam {.fits}]

	regsub $exp $cmd "cat \{$ianalysis($which,$i,start,fn)\} |" cmd
    }
}

proc ParseGetURLMacro {cmdname which i} {
    upvar $cmdname cmd
    global ianalysis

    set exp {\$geturl\((.*)\)}
    if {[regexp $exp $cmd foo ianalysis($which,$i,start,url)]} {
	set ianalysis($which,$i,start) geturl
	set ianalysis($which,$i,start,fn) [tmpnam {.fits}]

	regsub $exp $cmd {} cmd
    }
}

proc ParseImageMacro {cmdname which i} {
    upvar $cmdname cmd
    global ianalysis

    set exp {\|.?\$image\(([^)]*)\)}
if {[regexp $exp $cmd foo ianalysis($which,$i,image)]} {
    regsub $exp $cmd {} cmd
    
    set ianalysis($which,$i,finish) image
}

set exp {\|.?\$image}
if {[regexp $exp $cmd]} {
    regsub $exp $cmd {} cmd

    set ianalysis($which,$i,finish) image
}
}

proc AnalysisText {tt title txt method} {
    if {$txt != {} && $txt != "\n"} {
	SimpleTextDialog ${tt}txt $title 80 20 $method bottom $txt
    }
}

proc AnalysisMessage {type message} {
    if {$type == {}} {
	set type ok
    }

    switch -- [tk_messageBox -message $message -type $type] {
	ok -
	yes {return 1}
	cancel -
	default {return 0}
    }
}

proc AnalysisEntry {message resultvar} {
    upvar $resultvar result

    return [EntryDialog [msgcat::mc {Entry}] $message 60 result]
}

proc AnalysisPrefOpen {varname} {
    upvar $varname var

    FileLast analysisfbox $var
    set var [OpenFileDialog analysisfbox]
}

# Cmds

proc ProcessAnalysisCmd {varname iname buf fn} {
    upvar $varname var
    upvar $iname i

	global parse
	set parse(buf) $buf
	set parse(fn) $fn
	
	analysis::YY_FLUSH_BUFFER
	analysis::yy_scan_string [lrange $var $i end]
	analysis::yyparse
	incr i [expr $analysis::yycnt-1]
}

proc AnalysisCmdTask {task} {
    global ianalysis
    
    for {set ii 0} {$ii<$ianalysis(menu,count)} {incr ii} {
	if {[string equal -nocase $ianalysis(menu,$ii,item) $task]} {
	    AnalysisTask $ii menu
	}
    }
}

proc AnalysisCmdText {} {
    global parse
    
    if {$parse(buf) != {}} {
	AnalysisText apXPA Analysis $parse(buf) append
    } elseif {$parse(fn) != {}} {
	if {[file exists $parse(fn)]} {
	    set ch [open $parse(fn) r]
	    set txt [read $ch]
	    close $ch
	    AnalysisText apXPA Analysis $txt append
	}
    }
}

proc AnalysisCmdPlotStdin {} {
    global iap
    global parse
    
    if {$parse(buf) != {}} {
	AnalysisPlotStdin line $iap(tt) {} $parse(buf)
    } elseif {$parse(fn) != {}} {
	if {[file exists $parse(fn)]} {
	    set ch [open $parse(fn) r]
	    set rr [read $ch]
	    close $ch
	    AnalysisPlotStdin line $iap(tt) {} $rr
	}
    } else {
	AnalysisPlotStdin line $iap(tt) {} {}
    }
}

proc AnalysisCmdPlotLine {title xaxis yaxis dim} {
    global iap
    global parse

    if {$parse(buf) != {}} {
	PlotLine $iap(tt) Plot $title $xaxis $yaxis $dim $parse(buf)
    } elseif {$parse(fn) != {}} {
	if {[file exists $parse(fn)]} {
	    set ch [open $parse(fn) r]
	    set rr [read $ch]
	    close $ch
	    PlotLine $iap(tt) Plot $title $xaxis $yaxis $dim $rr
	}
    } else {
	PlotLine $iap(tt) Plot $title $xaxis $yaxis $dim {}
    }
}

proc AnalysisCmdLoad {} {
    global parse

    if {$parse(buf) != {}} {
	ProcessAnalysis parse(buf)
    } elseif {$parse(fn) != {}} {
	ProcessAnalysisFile $parse(fn)
    }
}

proc ProcessSendAnalysisCmd {proc id param sock fn} {
    global parse
    set parse(proc) $proc
    set parse(id) $id
    set parse(sock) $sock
    set parse(fn) $fn

    analysissend::YY_FLUSH_BUFFER
    analysissend::yy_scan_string $param
    analysissend::yyparse
}

proc AnalysisSendCmd {} {
    global parse
    global ianalysis

    for {set ii 0} {$ii<$ianalysis(menu,count)} {incr ii} {
	append result "\#$ii menu"
	append result "\n$ianalysis(menu,$ii,item)"
	append result "\n$ianalysis(menu,$ii,template)"
	if {$ianalysis(menu,$ii,cmd) != {web}} {
	    append result "\nmenu"
	    append result "\n$ianalysis(menu,$ii,cmd)"
	} else {
	    append result "\n$ianalysis(menu,$ii,cmd)"
	    append result "\n$ianalysis(menu,$ii,var)"
	}
	append result "\n\n"
    }
    for {set ii 0} {$ii<$ianalysis(bind,count)} {incr ii} {
	set key [string range $ianalysis(bind,$ii,item) 1 1]
	append result "\#$ii bind"
	append result "\nbind key $ianalysis(bind,$ii,item)"
	append result "\n$ianalysis(bind,$ii,template)"
	append result "\nbind $key"
	append result "\n$ianalysis(bind,$ii,cmd)"
	append result "\n\n"
    }

    ProcessSend $parse(proc) $parse(id) $parse(sock) $parse(fn) {.ans} $result
}

proc AnalysisSendCmdEntry {txt} {
    set result {}
    AnalysisEntry $txt result
    ProcessSendCmdTxt $result
}

proc AnalysisSendCmdMessage {type txt} {
    ProcessSendCmdTxt [AnalysisMessage $type $txt]
}

proc AnalysisSendCmdTask {} {
    global ianalysis

    # invoke by name
    for {set ii 0} {$ii<$ianalysis(menu,count)} {incr ii} {
	append result "$ii $ianalysis(menu,$ii,item)\n"
    }

    ProcessSendCmdTxt $result
}