summaryrefslogtreecommitdiffstats
path: root/ds9/library/contour.tcl
blob: 44e32b9e2726fb4cad58fc759b49363551fd68c4 (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
#  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 ContourDef {} {
    global contour
    global icontour
    global pcontour

    set icontour(top) .ct
    set icontour(mb) .ctmb

    set contour(view) 0
    set contour(copy) {}

    set contour(color) green
    set contour(width) 1
    set contour(dash) 0

    set contour(method) block
    set contour(smooth) 4
    set contour(numlevel) 5

    set contour(scale) linear
    set contour(mode) minmax
    set contour(log) 1000
    set contour(scope) local
    set contour(min) {}
    set contour(max) {}

    # used for command line options
    # example % ds9 -contour log foo.fits -zscale -contour
    # .. contour scale is log, not zscale
    set contour(init,scale) 0
    set contour(init,mode) 0
    set contour(init,scope) 0
    set contour(init,limits) 0

    set pcontour(view) $contour(view)
    set pcontour(method) $contour(method)
    set pcontour(color) $contour(color)
    set pcontour(width) $contour(width)
    set pcontour(dash) $contour(dash)
    set pcontour(smooth) $contour(smooth)
    set pcontour(numlevel) $contour(numlevel)
}

proc UpdateContour {} {
    global contour
    global icontour
    global dcontour
    global current

    global debug
    if {$debug(tcl,update)} {
	puts stderr "UpdateContour"
    }

    if {$current(frame) == {}} {
	return
    }
    if {![$current(frame) has fits]} {
	return
    }

    if {!$contour(view)} {
	$current(frame) contour delete
	return
    }	

    ContourCheckParams
    if {[winfo exists $icontour(top)]} {
	set levels [$dcontour(txt) get 1.0 end]
	# remove endl and trim
	regsub -all "\n" $levels " " levels
	set levels [string trimright $levels " "]

	if {$levels == {}} {
	    ContourGenerateDialog
	    set levels [$dcontour(txt) get 1.0 end]
	    # remove endl and trim
	    regsub -all "\n" $levels " " levels
	    set levels [string trimright $levels " "]
	}

	if {$levels != {} && [ContourCheckMinMax]} {
    $current(frame) contour create \
		$contour(color) $contour(width) $contour(dash) \
		$contour(method) $contour(numlevel) $contour(smooth) \
		$contour(scale) $contour(log) $contour(mode) $contour(scope) \
		$contour(min) $contour(max) \
		"\"$levels\""
	}
    } else {
	set contour(scale) [$current(frame) get colorscale]
	set contour(log) [$current(frame) get colorscale log]
	set contour(mode) [$current(frame) get clip mode]
	set contour(scope) [$current(frame) get clip scope]
	set limits [$current(frame) get clip $contour(mode) $contour(scope)]
	set contour(min) [lindex $limits 0]
	set contour(max) [lindex $limits 1]

	if {[ContourCheckMinMax]} {
	    $current(frame) contour create \
		$contour(color) $contour(width) $contour(dash) \
		$contour(method) $contour(numlevel) $contour(smooth) \
		$contour(scale) $contour(log) $contour(mode) $contour(scope) \
		$contour(min) $contour(max) \
		"{}"
	}
    }
}

proc ContourCheckParams {} {
    global contour

    if {$contour(smooth) < 1} {
	set contour(smooth) 1
    }
    if {$contour(numlevel) < 1} {
	set contour(numlevel) 1
    }
}

proc ContourCheckMinMax {} {
    global contour

    if {$contour(min) != {} &&
	$contour(max) != {} &&
	!($contour(min) eq "nan") &&
	!($contour(max) eq "nan") &&
	[string is double $contour(min)] && 
	[string is double $contour(max)]
    } {
	return 1
    } else {
	return 0
    }
}

proc ContourDialog {} {
    global contour
    global icontour
    global dcontour
    global current
    global ds9

    # see if we already have a ctr window visible
    if {[winfo exists $icontour(top)]} {
	raise $icontour(top)
	return
    }

    # create the contour window
    set w $icontour(top)
    set mb $icontour(mb)

    Toplevel $w $mb 6 [msgcat::mc {Contour Parameters}] ContourDestroyDialog

    # local variables
    $mb add cascade -label [msgcat::mc {File}] -menu $mb.file
    $mb add cascade -label [msgcat::mc {Edit}] -menu $mb.edit
    $mb add cascade -label [msgcat::mc {Color}] -menu $mb.color
    $mb add cascade -label [msgcat::mc {Width}] -menu $mb.width
    $mb add cascade -label [msgcat::mc {Scale}] -menu $mb.scale
    $mb add cascade -label [msgcat::mc {Limits}] -menu $mb.limit
    $mb add cascade -label [msgcat::mc {Scope}] -menu $mb.scope
    $mb add cascade -label [msgcat::mc {Method}] -menu $mb.method

    menu $mb.file
    $mb.file add command -label [msgcat::mc {Apply}] \
	-command ContourApplyDialog
    $mb.file add command -label [msgcat::mc {Generate}] \
	-command ContourGenerateDialog
    $mb.file add command -label [msgcat::mc {Clear}] \
	-command ContourOffDialog
    $mb.file add separator
    $mb.file add command -label [msgcat::mc {Copy Contours}] \
	-command ContourCCopyDialog
    $mb.file add command -label "[msgcat::mc {Paste Contours}]..." \
	-command ContourCPasteDialog
    $mb.file add separator
    $mb.file add command -label "[msgcat::mc {Load Contours}]..." \
	-command ContourLoadDialog
    $mb.file add command -label "[msgcat::mc {Save Contours}]..." \
	-command ContourSaveDialog
    $mb.file add separator
    $mb.file add command -label "[msgcat::mc {Load Contour Levels}]..." \
	-command ContourLoadLevels
    $mb.file add command -label "[msgcat::mc {Save Contour Levels}]..." \
	-command ContourSaveLevels
    $mb.file add separator
    $mb.file add command -label [msgcat::mc {Convert to Polygons}] \
	-command Contour2Polygons
    $mb.file add separator
    $mb.file add command -label [msgcat::mc {Close}] \
	-command ContourDestroyDialog

    menu $mb.edit
    $mb.edit add command -label [msgcat::mc {Cut}] \
	-command ContourCutDialog -accelerator "${ds9(ctrl)}X"
    $mb.edit add command -label [msgcat::mc {Copy}] \
	-command ContourCopyDialog -accelerator "${ds9(ctrl)}C"
    $mb.edit add command -label [msgcat::mc {Paste}] \
	-command ContourPasteDialog -accelerator "${ds9(ctrl)}V"

    ColorMenu $mb.color contour color {}
    WidthDashMenu $mb.width contour width dash {} {}

    menu $mb.scale
    $mb.scale add radiobutton -label [msgcat::mc {Linear}] \
	-variable contour(scale) -value linear
    $mb.scale add radiobutton -label [msgcat::mc {Log}] \
	-variable contour(scale) -value log
    $mb.scale add radiobutton -label [msgcat::mc {Power}] \
	-variable contour(scale) -value pow
    $mb.scale add radiobutton -label [msgcat::mc {Square Root}] \
	-variable contour(scale) -value sqrt
    $mb.scale add radiobutton -label [msgcat::mc {Squared}] \
	-variable contour(scale) -value squared
    $mb.scale add radiobutton -label {ASINH} \
	-variable contour(scale) -value asinh
    $mb.scale add radiobutton -label {SINH} \
	-variable contour(scale) -value sinh
    $mb.scale add radiobutton \
	-label [msgcat::mc {Histogram Equalization}] \
	-variable contour(scale) -value histequ
    $mb.scale add separator
    $mb.scale add command -label "[msgcat::mc {Log Exponent}]..." \
	-command ContourLogDialog

    menu $mb.limit
    $mb.limit add radiobutton -label [msgcat::mc {Min Max}] \
	-variable contour(mode) -value minmax -command ContourModeDialog
    $mb.limit add separator
    $mb.limit add radiobutton -label {99.5%} \
	-variable contour(mode) -value 99.5 -command ContourModeDialog
    $mb.limit add radiobutton -label {99%} \
	-variable contour(mode) -value 99 -command ContourModeDialog
    $mb.limit add radiobutton -label {98%} \
	-variable contour(mode) -value 98 -command ContourModeDialog
    $mb.limit add radiobutton -label {95%} \
	-variable contour(mode) -value 95 -command ContourModeDialog
    $mb.limit add radiobutton -label {90%} \
	-variable contour(mode) -value 90 -command ContourModeDialog
    $mb.limit add separator
    $mb.limit add radiobutton -label {ZScale} \
	-variable contour(mode) -value zscale -command ContourModeDialog
    $mb.limit add radiobutton -label {ZMax} \
	-variable contour(mode) -value zmax -command ContourModeDialog
    $mb.limit add radiobutton -label [msgcat::mc {User}] \
	-variable contour(mode) -value user -command ContourModeDialog

    menu $mb.scope 
    $mb.scope add radiobutton -label [msgcat::mc {Global}] \
	-variable contour(scope) -value global -command ContourModeDialog
    $mb.scope add radiobutton -label [msgcat::mc {Local}] \
	-variable contour(scope) -value local -command ContourModeDialog

    menu $mb.method
    $mb.method add radiobutton -label [msgcat::mc {Block}] \
	-variable contour(method) -value block
    $mb.method add radiobutton -label [msgcat::mc {Smooth}] \
	-variable contour(method) -value smooth

    # Param
    set f [ttk::labelframe $w.param -text [msgcat::mc {Contour}] -padding 2]

    slider $f.nslider 0 50 [msgcat::mc {Levels}] contour(numlevel) {}
    slider $f.rslider 0 32 [msgcat::mc {Smoothness}] contour(smooth) {}

    ttk::label $f.title -text [msgcat::mc {Limits}]
    ttk::label $f.ltitle -text [msgcat::mc {Low}]
    ttk::entry $f.low -textvariable contour(min) -width 10
    ttk::label $f.htitle -text [msgcat::mc {High}]
    ttk::entry $f.high -textvariable contour(max) -width 10

    grid $f.nslider -columnspan 6 -padx 2 -pady 2
    grid $f.rslider -columnspan 6 -padx 2 -pady 2
    grid $f.title $f.ltitle $f.low $f.htitle $f.high -padx 2 -pady 2

    # Levels
    set f [ttk::labelframe $w.levels -text [msgcat::mc {Levels}] -padding 2]

    set dcontour(txt) [text $f.text \
			   -wrap none \
			   -width 15 \
			   -height 10 \
			   -font [font actual TkDefaultFont] \
			   -yscrollcommand [list $f.yscroll set] \
		      ]
    ttk::scrollbar $f.yscroll -command [list $dcontour(txt) yview] \
	-orient vertical

    grid $f.text $f.yscroll -sticky news
    grid rowconfigure $f 0 -weight 1
    grid columnconfigure $f 0 -weight 1

    # Buttons
    set f [ttk::frame $w.buttons]
    ttk::button $f.apply -text [msgcat::mc {Apply}] \
	-command ContourApplyDialog
    ttk::button $f.generate -text [msgcat::mc {Generate}] \
	-command ContourGenerateDialog
    ttk::button $f.clear -text [msgcat::mc {Clear}] \
	-command ContourOffDialog
    ttk::button $f.close -text [msgcat::mc {Close}] \
	-command ContourDestroyDialog
    pack $f.apply $f.generate $f.clear $f.close \
	-side left -expand true -padx 2 -pady 4

    # Fini
    grid $w.param $w.levels -sticky news
    grid $w.buttons - -sticky ew
    grid rowconfigure $w 0 -weight 1
    grid columnconfigure $w 1 -weight 1

    UpdateContourDialog
}

proc ContourApplyDialog {} {
    global contour

    set contour(view) 1
    UpdateContour
}

proc ContourDestroyDialog {} {
    global contour
    global icontour
    global dcontour

    if {[winfo exists $icontour(top)]} {
	destroy $icontour(top)
	destroy $icontour(mb)
	unset dcontour
    }
}

proc ContourGenerateDialog {} {
    global contour
    global dcontour
    global current

    ContourCheckParams

    $dcontour(txt) delete 1.0 end
    if {$current(frame) != {}} {
	if {([$current(frame) has fits]) && [ContourCheckMinMax]} {
	    set ll [$current(frame) get colorscale level $contour(numlevel) \
			$contour(min) $contour(max) \
			$contour(scale) $contour(log)]
	    regsub -all " " "$ll" "\n" ll
	    $dcontour(txt) insert end "$ll"
	}
    }
}

proc ContourOffDialog {} {
    global contour
    global current

    set contour(view) 0
    if {$current(frame) != {}} {
	$current(frame) contour delete
	$current(frame) contour delete aux
    }
    UpdateContourScale
    UpdateContourDialog
}

proc ContourCutDialog {} {
    global icontour
    global dcontour

    if {[winfo exists $icontour(top)]} {
	set w [focus -displayof $icontour(top)]
	if {$w == $dcontour(txt)} {
	    tk_textCut $w
	} else {
	    EntryCut $icontour(top)
	}
    }
}

proc ContourCopyDialog {} {
    global icontour
    global dcontour

    if {[winfo exists $icontour(top)]} {
	set w [focus -displayof $icontour(top)]
	if {$w == $dcontour(txt)} {
	    tk_textCopy $w
	} else {
	    EntryCopy $icontour(top)
	}
    }
}

proc ContourPasteDialog {} {
    global icontour
    global dcontour

    if {[winfo exists $icontour(top)]} {
	set w [focus -displayof $icontour(top)]
	if {$w == $dcontour(txt)} {
	    tk_textPaste $w
	} else {
	    EntryPaste $icontour(top)
	}
    }
}

proc ContourCCopyDialog {} {
    global contour
    global current

    set contour(copy) $current(frame)
    UpdateContourDialog
}

proc ContourCPasteDialog {} {
    global ds9
    global current
    global contour
    global ed

    if {$current(frame) == {} || $contour(copy) == {}} {
	return
    }

    set w {.ctld}

    set ed(ok) 0
    set ed(system) wcs
    set ed(sky) fk5
    set ed(color) green
    set ed(width) 1
    set ed(dash) 0
    set ed(frame) $current(frame)
    set ed(original) 0

    SetCoordSystem ed system sky {}
    AdjustCoordSystem ed system

    DialogCreate $w [msgcat::mc {Contour Paste}] ed(ok)

    # Param
    set f [ttk::frame $w.param1]

    ttk::checkbutton $f.original -text [msgcat::mc {Use Original Color/Width}] -variable ed(original)
    grid $f.original -padx 2 -pady 2 -sticky w

    set f [ttk::frame $w.param]

    ttk::label $f.coordtitle -text [msgcat::mc {Coordinate System}]

    CoordMenuButton $f.coordbutton ed system 1 {} {} {}
    CoordMenuEnable $f.coordbutton.menu ed system 1 {} {}

    ttk::label $f.colortitle -text [msgcat::mc {Color}]
    ColorMenuButton $f.colorbutton ed color {}

    ttk::label $f.widthtitle -text [msgcat::mc {Width}]
    ttk::menubutton $f.widthbutton -textvariable ed(width) \
	-menu $f.widthbutton.menu
    WidthDashMenu $f.widthbutton.menu ed width dash {} {}

    grid $f.coordtitle $f.coordbutton -padx 2 -pady 2 -sticky w
    grid $f.colortitle $f.colorbutton -padx 2 -pady 2 -sticky w
    grid $f.widthtitle $f.widthbutton -padx 2 -pady 2 -sticky w

    # Buttons
    set f [ttk::frame $w.buttons]
    ttk::button $f.ok -text [msgcat::mc {OK}] -command {set ed(ok) 1} \
	-default active 
    ttk::button $f.cancel -text [msgcat::mc {Cancel}] -command {set ed(ok) 0}
    pack $f.ok $f.cancel -side left -expand true -padx 2 -pady 4

    bind $w <Return> {set ed(ok) 1}

    # Fini
    ttk::separator $w.sep -orient horizontal
    ttk::separator $w.sep2 -orient horizontal
    pack $w.buttons $w.sep -side bottom -fill x
    pack $w.param1 $w.sep2 $w.param -side top -fill both -expand true
#    pack $w.param -side top -fill both -expand true

    DialogCenter $w 
    DialogWait $w ed(ok)
    DialogDismiss $w

    if {$ed(ok)} {
	set ed(color) [string tolower $ed(color)]

	if {$current(frame) == $contour(copy)} {
	    set ed(system) physical
	}

	set cc [$contour(copy) get contour $ed(system) fk5]
	if {$ed(original)} {
	    $current(frame) contour paste cc
	} else {
	    $current(frame) contour paste cc $ed(color) $ed(width) $ed(dash)
	}
	UpdateContourDialog
    }

    set rr $ed(ok)
    unset ed
    return $rr
}

proc ContourModeDialog {} {
    global current
    global contour

    if {$current(frame) != {}} {
	set limits [$current(frame) get clip $contour(mode) $contour(scope)]
	set contour(min) [lindex $limits 0]
	set contour(max) [lindex $limits 1]
    }
}

proc ContourLoadLevels {} {
    set fn [OpenFileDialog contourlevlfbox]

    ContourLoadLevelsNow $fn
}

proc ContourLoadLevelsNow {fn} {
    global dcontour

    if {$fn == {}} {
	return
    }

    $dcontour(txt) delete 1.0 end
    set ch [open $fn r]
    if {[file extension $fn] == {.lev}} {
	$dcontour(txt) insert end [read $ch]
    } else {
	ContourLoadLevelsNew $ch
    }
    close $ch
}

proc ContourLoadLevelsNew {ch} {
    global dcontour

    while {[gets $ch line] != -1} {
	set aa [split $line {= }]
	regsub -all {[{}]} $aa {} aa
	regsub -all { +} $aa { } aa
	set aa [string trim $aa]

	if {![string compare -nocase [lindex $aa 0] {level}]} {
	    set value [string trim [lindex $aa 1]]
	    if {[string is double $value]} {
		$dcontour(txt) insert end "$value\n"
	    }
	}
    }
}

proc ContourSaveLevels {} {
    set fn [SaveFileDialog contourlevsfbox]
    ContourSaveLevelsNow $fn
}

proc ContourSaveLevelsNow {fn} {
    global dcontour

    if {$fn == {}} {
	return
    }

    set id [open $fn w]
    puts -nonewline $id "[$dcontour(txt) get 1.0 end]"
    close $id
}

proc ContourSaveDialog {} {
    global ds9
    global current
    global contour
    global ed
    global wcs

    set fn [SaveFileDialog contoursfbox]

    if {$fn == {} || $current(frame) == {}} {
	return
    }

    set w {.ctld}

    set ed(ok) 0
    set ed(system) wcs
    set ed(sky) fk5
    set ed(skyformat) degrees
    set ed(frame) $current(frame)

    SetCoordSystem ed system sky {}
    AdjustCoordSystem ed system

    DialogCreate $w [msgcat::mc {Contour Save}] ed(ok)

    # Param
    set f [ttk::frame $w.param]

    ttk::label $f.coordtitle -text [msgcat::mc {Coordinate System}]

    CoordMenuButton $f.coordbutton ed system 1 sky skyformat {}
    CoordMenuEnable $f.coordbutton.menu ed system 1 sky skyformat
    grid $f.coordtitle $f.coordbutton -padx 2 -pady 2 -sticky w

    # Buttons
    set f [ttk::frame $w.buttons]
    ttk::button $f.ok -text [msgcat::mc {OK}] -command {set ed(ok) 1} \
	-default active 
    ttk::button $f.cancel -text [msgcat::mc {Cancel}] -command {set ed(ok) 0}
    pack $f.ok $f.cancel -side left -expand true -padx 2 -pady 4

    bind $w <Return> {set ed(ok) 1}

    # Fini
    ttk::separator $w.sep -orient horizontal
    pack $w.buttons $w.sep -side bottom -fill x
    pack $w.param -side top -fill both -expand true

    DialogCenter $w 
    DialogWait $w ed(ok)
    DialogDismiss $w

    if {$ed(ok)} {
	switch -- $ed(system) {
	    image -
	    physical -
	    detector -
	    amplifier {}
	    default {
		if {![$current(frame) has wcs $ed(system)]} {
		    Error "[msgcat::mc {Invalid WCS}] $ed(system)"
		    return $ed(ok)
		}
	    }
	}

	$current(frame) contour save "\{$fn\}" $ed(system) $ed(sky)
	UpdateContourDialog
    }

    set rr $ed(ok)
    unset ed
    return $rr
}

proc ContourLoadDialog {} {
    global ds9
    global current
    global contour
    global ed

    set fn [OpenFileDialog contourlfbox]

    if {$fn == {} || $current(frame) == {}} {
	return
    }

    set w {.ctld}

    set ed(ok) 0
    set ed(color) green
    set ed(width) 1
    set ed(dash) 0
    set ed(frame) $current(frame)
    set ed(original) 0
    if {[file extension $fn] == {.con}} {
	ContourLoadOldDialog $fn
    } else {
	ContourLoadNewDialog $fn
    }
}

proc ContourLoadOldDialog {fn} {
    global ds9
    global current
    global contour
    global ed

    set w {.ctld}

    set ed(ok) 0
    set ed(system) wcs
    set ed(sky) fk5
    set ed(color) green
    set ed(width) 1
    set ed(dash) 0
    set ed(frame) $current(frame)

    SetCoordSystem ed system sky {}
    AdjustCoordSystem ed system

    DialogCreate $w [msgcat::mc {Contour Paste}] ed(ok)

    # Param
    set f [ttk::frame $w.param]

    ttk::label $f.coordtitle -text [msgcat::mc {Coordinate System}]

    CoordMenuButton $f.coordbutton ed system 1 {} {} {}
    CoordMenuEnable $f.coordbutton.menu ed system 1 {} {}

    ttk::label $f.colortitle -text [msgcat::mc {Color}]
    ColorMenuButton $f.colorbutton ed color {}

    ttk::label $f.widthtitle -text [msgcat::mc {Width}]
    ttk::menubutton $f.widthbutton -textvariable ed(width) \
	-menu $f.widthbutton.menu
    WidthDashMenu $f.widthbutton.menu ed width dash {} {}

    grid $f.coordtitle $f.coordbutton -padx 2 -pady 2 -sticky w
    grid $f.colortitle $f.colorbutton -padx 2 -pady 2 -sticky w
    grid $f.widthtitle $f.widthbutton -padx 2 -pady 2 -sticky w

    # Buttons
    set f [ttk::frame $w.buttons]
    ttk::button $f.ok -text [msgcat::mc {OK}] -command {set ed(ok) 1} \
	-default active 
    ttk::button $f.cancel -text [msgcat::mc {Cancel}] -command {set ed(ok) 0}
    pack $f.ok $f.cancel -side left -expand true -padx 2 -pady 4

    bind $w <Return> {set ed(ok) 1}

    # Fini
    ttk::separator $w.sep -orient horizontal
    pack $w.buttons $w.sep -side bottom -fill x
    pack $w.param -side top -fill both -expand true

    DialogCenter $w 
    DialogWait $w ed(ok)
    DialogDismiss $w

    if {$ed(ok)} {
	set ed(color) [string tolower $ed(color)]
	$current(frame) contour load $ed(color) $ed(width) $ed(dash) \
	    "\{$fn\}" $ed(system) $ed(sky)
	UpdateContourDialog
    }

    set rr $ed(ok)
    unset ed
    return $rr
}

proc ContourLoadNewDialog {fn} {
    global ds9
    global current
    global contour
    global ed

    set w {.ctld}

    set ed(ok) 0
    set ed(color) green
    set ed(width) 1
    set ed(dash) 0
    set ed(frame) $current(frame)
    set ed(original) 0

    DialogCreate $w [msgcat::mc {Contour Paste}] ed(ok)

    # Param
    set f [ttk::frame $w.param1]

    ttk::checkbutton $f.original -text [msgcat::mc {Use Original Color/Width}] \
	-variable ed(original)

    grid $f.original -padx 2 -pady 2 -sticky w

    set f [ttk::frame $w.param2]

    ttk::label $f.colortitle -text [msgcat::mc {Color}]
    ColorMenuButton $f.colorbutton ed color {}

    ttk::label $f.widthtitle -text [msgcat::mc {Width}]
    ttk::menubutton $f.widthbutton -textvariable ed(width) \
	-menu $f.widthbutton.menu
    WidthDashMenu $f.widthbutton.menu ed width dash {} {}

    grid $f.colortitle $f.colorbutton -padx 2 -pady 2 -sticky w
    grid $f.widthtitle $f.widthbutton -padx 2 -pady 2 -sticky w

    # Buttons
    set f [ttk::frame $w.buttons]
    ttk::button $f.ok -text [msgcat::mc {OK}] -command {set ed(ok) 1} \
	-default active 
    ttk::button $f.cancel -text [msgcat::mc {Cancel}] -command {set ed(ok) 0}
    pack $f.ok $f.cancel -side left -expand true -padx 2 -pady 4

    bind $w <Return> {set ed(ok) 1}

    # Fini
    ttk::separator $w.sep -orient horizontal
    ttk::separator $w.sep2 -orient horizontal
    pack $w.buttons $w.sep -side bottom -fill x
    pack $w.param1 $w.sep2 $w.param2 -side top -fill both -expand true

    DialogCenter $w 
    DialogWait $w ed(ok)
    DialogDismiss $w

    if {$ed(ok)} {
	set ed(color) [string tolower $ed(color)]

	if {$ed(original)} {
	    $current(frame) contour load "\{$fn\}"
	} else {
	    $current(frame) contour load "\{$fn\}" \
		$ed(color) $ed(width) $ed(dash)
	}
	UpdateContourDialog
    }

    set rr $ed(ok)
    unset ed
    return $rr
}

proc Contour2Polygons {} {
    global current
    global contour

    if {$current(frame) != {}} {
	$current(frame) contour create polygon
	$current(frame) contour delete
    }    
}

proc UpdateContourMenu {} {
    global contour
    global current

    global debug
    if {$debug(tcl,update)} {
	puts stderr "UpdateContourMenu"
    }

    if {$current(frame) == {}} {
	return
    }
    if {![$current(frame) has fits]} {
	return
    }

    set contour(view) [$current(frame) has contour]

    if {[$current(frame) has contour]} {
	set contour(color) [$current(frame) get contour color]
	set contour(width) [$current(frame) get contour width]
	set contour(dash) [$current(frame) get contour dash]
	set contour(method) [$current(frame) get contour method]
	set contour(smooth) [$current(frame) get contour smooth]
	set contour(numlevel) [$current(frame) get contour number level]
    }

    UpdateContourScale
}

proc UpdateContourScale {} {
    global contour
    global current
    global ds9

    global debug
    if {$debug(tcl,update)} {
	puts stderr "UpdateContourScale"
    }

    if {$current(frame) == {}} {
	return
    }
    if {![$current(frame) has fits]} {
	return
    }

    if {[$current(frame) has contour]} {
	set contour(scale) [$current(frame) get contour colorscale]
	set contour(mode) [$current(frame) get contour clip mode]
	set contour(scope) [$current(frame) get contour clip scope]
	set contour(log) [$current(frame) get contour colorscale log]
	set limits [$current(frame) get contour clip]
	set contour(min) [lindex $limits 0]
	set contour(max) [lindex $limits 1]
    } else {
	if {!($ds9(init) && $contour(init,scale))} {
	    set contour(scale) [$current(frame) get colorscale]
	    set contour(log) [$current(frame) get colorscale log]
	}
	if {!($ds9(init) && $contour(init,mode))} {
	    set contour(mode) [$current(frame) get clip mode]
	}
	if {!($ds9(init) && $contour(init,scope))} {
	    set contour(scope) [$current(frame) get clip scope]
	}
	if {!($ds9(init) && $contour(init,limits))} {
	    set limits [$current(frame) get clip $contour(mode) $contour(scope)]
	    set contour(min) [lindex $limits 0]
	    set contour(max) [lindex $limits 1]
	}
    }
}

proc UpdateContourDialog {} {
    global contour
    global icontour
    global dcontour
    global current

    global debug
    if {$debug(tcl,update)} {
	puts stderr "UpdateContourDialog"
    }

    if {![winfo exists $icontour(top)]} {
	return
    }

    if {$current(frame) == {}} {
	return
    }
    if {![$current(frame) has fits]} {
	return
    }

    if {[$current(frame) has contour]} {
	set levels [$current(frame) get contour level]
	regsub -all "\n" "$levels" " " levels
	set levels [join $levels "\n"]
	if {$levels != {}} {
	    $dcontour(txt) delete 1.0 end
	    $dcontour(txt) insert end $levels
	} else {
	    ContourGenerateDialog
	}
    } else {
	ContourGenerateDialog
    }
}

proc ContourLogDialog {} {
    global contour

    EntryDialog [msgcat::mc {Scale}] [msgcat::mc {Log Exponent}] 10 contour(log)
}

proc ContourBackup {ch which fdir rdir} {
    switch [$which get type] {
	base -
	3d {ContourBackupBase $ch $which $fdir $rdir}
	rgb {ContourBackupRGB $ch $which $fdir $rdir}
    }
}

proc ContourBackupBase {ch which fdir rdir} {
    if {[$which has contour]} {
	set color [$which get contour color]
	set width [$which get contour width]
	set dash [$which get contour dash]
	set method [$which get contour method]
	set numlevel [$which get contour number level]
	set smooth [$which get contour smooth]
	set scale [$which get contour colorscale]
	set log [$which get contour colorscale log]
	set mode [$which get contour clip mode]
	set scope [$which get contour clip scope]
	set limits [$which get contour clip]
	set levels [$which get contour level]

	puts $ch "$which contour create $color $width $dash $method $numlevel $smooth $scale $log $mode $scope $limits \{\"$levels\"\}"
    }

    # delete old contours
    foreach ff [glob -directory $fdir -nocomplain "aux*.ctr"] {
	catch {file delete -force $ff}
    }

    if {[$which has contour aux]} {
	set fn $fdir/aux.ctr
	set rfn $rdir/aux.ctr
	$which contour save aux \"$fn\" physical fk5
	puts $ch "$which contour load \{\"$rfn\"\}"
    }
}

proc ContourBackupRGB {ch which fdir rdir} {
    set sav [$which get rgb channel]
    foreach cc {red green blue} {
	$which rgb channel $cc
	puts $ch "$which rgb channel $cc"
	ContourBackupBase $ch $which $fdir $rdir
    }
    $which rgb channel $sav
    puts $ch "$which rgb channel $sav"
}

proc PrefsDialogContour {} {
    global dprefs

    set w $dprefs(tab)

    $dprefs(list) insert end [msgcat::mc {Contours}]
    lappend dprefs(tabs) [ttk::frame $w.contour]

    set f [ttk::labelframe $w.contour.param -text [msgcat::mc {Contours}]]

    ttk::label $f.mtitle -text [msgcat::mc {Method}]
    ttk::menubutton $f.method -textvariable pcontour(method) \
	-menu $f.method.menu

    global pcontour
    ttk::label $f.ctitle -text [msgcat::mc {Color}]
    ColorMenuButton $f.color pcontour color {}

    ttk::label $f.wtitle -text [msgcat::mc {Width}]
    ttk::menubutton $f.width -textvariable pcontour(width) -menu $f.width.menu
    WidthDashMenu $f.width.menu pcontour width dash {} {}

    grid $f.mtitle $f.method -padx 2 -pady 2 -sticky w
    grid $f.ctitle $f.color -padx 2 -pady 2 -sticky w
    grid $f.wtitle $f.width -padx 2 -pady 2 -sticky w

    set m $f.method.menu 
    menu $m
    $m add radiobutton -label [msgcat::mc {Block}] \
	-variable pcontour(method) -value block
    $m add radiobutton -label [msgcat::mc {Smooth}] \
	-variable pcontour(method) -value smooth

    pack $f -side top -fill both -expand true
}

proc ProcessContourCmd {varname iname} {
    upvar $varname var
    upvar $iname i

    # we need to be realized
    ProcessRealizeDS9

    contour::YY_FLUSH_BUFFER
    contour::yy_scan_string [lrange $var $i end]
    contour::yyparse
    incr i [expr $contour::yycnt-1]
}

proc ContourCmdLoad {fn} {
    global current

    if {$current(frame) != {} && $fn != {}} {
	$current(frame) contour load $fn
	FileLast contourlfbox $fn
	UpdateContourDialog
    }
}

proc ContourCmdLoadOrg {fn sys sky color width dash} {
    global current

    if {$current(frame) != {} && $fn != {}} {
	$current(frame) contour load $color $width $dash $fn $sys $sky
	FileLast contourlfbox $fn
	UpdateContourDialog
    }
}

proc ContourCmdSave {fn sys sky} {
    global current

    if {$current(frame) != {} && $fn != {}} {
	$current(frame) contour save $fn $sys $sky
	FileLast contoursfbox $fn
    }
}

proc ContourCmdLoadLevels {fn} {
    global current

    ContourDialog
    if {$current(frame) != {}} {
	ContourLoadLevelsNow $fn
	UpdateContour
    }
}

proc ContourCmdSaveLevels {fn} {
    global current

    ContourDialog
    if {$current(frame) != {}} {
	ContourSaveLevelsNow $fn
    }
}

proc ContourCmdPaste {sys sky color width dash} {
    global current
    global contour

    if {$current(frame) != {} && $contour(copy) != {}} {
	set cc [$contour(copy) get contour $sys $sky]
	$current(frame) contour paste cc $color $width $dash
    }
}

proc ContourCmdGenerateDialog {which value} {
    global contour

    ContourDialog
    set contour($which) $value
    ContourGenerateDialog
    UpdateContour
}

proc ContourCmdScale {which value} {
    global contour

    set contour(init,scale) 1
    ContourDialog

    set contour($which) $value
    ContourGenerateDialog
    UpdateContour
}

proc ContourCmdMode {which value} {
    global contour

    set contour(init,$which) 1
    ContourDialog

    set contour($which) $value
    ContourModeDialog
    ContourGenerateDialog
    UpdateContour
}

proc ContourCmdLimits {min max} {
    global contour

    set contour(init,limits) 1
    ContourDialog

    set contour(min) $min
    set contour(max) $max
    set contour(mode) user
    ContourGenerateDialog
    UpdateContour
}

proc ContourCmdLevels {str} {
    global dcontour

    ContourDialog
    $dcontour(txt) delete 1.0 end
    $dcontour(txt) insert end $str
    UpdateContour
}

proc ContourCmdGenerate {} {
    ContourDialog
    ContourGenerateDialog
    UpdateContour
}

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

    contoursend::YY_FLUSH_BUFFER
    contoursend::yy_scan_string $param
    contoursend::yyparse
}

proc ContourSendCmdLimits {} {
    global parse
    global contour

    $parse(proc) $parse(id) "$contour(min) $contour(max)\n"
}

proc ContourSendCmdLevels {} {
    global parse
    global dcontour

    ContourDialog
    $parse(proc) $parse(id) "[$dcontour(txt) get 1.0 end]"
}