aboutsummaryrefslogtreecommitdiff
path: root/noao/onedspec/t_sfit.x
blob: 54e896bb479309a294f0c9cb2eff4757ccaefb62 (plain) (blame)
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
include	<imhdr.h>
include <pkg/gtools.h>
include <pkg/rg.h>
include <math/curfit.h>
include	<error.h>
include	<smw.h>

# SFIT -- Fit a function to spectra and output the fit, difference or
# ratio; or print the power series coefficients of the fit.  The fitting
# parameters may be set interactively using the icfit package.

# Image header keywords for saving the previous fit

define	SFT_KW		"SFIT"
define	SFT_KWB		"SFITB"

# Choices for the type of output

define	OUT_TYPES	"|data|fit|difference|ratio|"

define	DATA		1
define	FIT		2
define	DIFFERENCE	3
define	RATIO		4

# Choices for the interactive prompts
# (the 1st define is for clgwrd (strdic), the 2nd for CL enumeration)
# Note that the CL assumes that the separator is `|'.

define	SFT_ANS1	"|yes|no|skip|YES|NO|SKIP|"
define	SFT_ANS1X	"yes|no|skip|YES|NO|SKIP"

define	SFT_ANS2	"|spectrum|image|all|cancel|"
define	SFT_ANS2X	"spectrum|image|all|cancel"

define	LEN_ANS		7

define	YES_ONCE	1
define	NO_ONCE		2
define	SKIP_ONCE	3
define	YES_ALWAYS	4
define	NO_ALWAYS	5
define	SKIP_ALWAYS	6

define	SKIP_SPEC	1
define	SKIP_IMAGE	2
define	SKIP_ALL	3
define	SKIP_CANCEL	4

# Switches and pointers

define	SFT_OFF		22

define	INTERACTIVE	Memi[$1]		# all spectra are noninteractive
define	REPLACE		Memi[$1+1]		# replace rejected points?
define	WAVESCALE	Memi[$1+2]		# X is wavelength if possible
define	LOGSCALE	Memi[$1+3]		# axes are logarithmic
define	OVERRIDE	Memi[$1+4]		# allow lines to be redone
define	LISTONLY	Memi[$1+5]		# don't modify images
define	OUTTYPE		Memi[$1+6]		# output type code

define	GRAPH_OPEN	Memi[$1+7]		# keep track of gopen
define	LOG_TO_STDOUT	Memi[$1+8]		# STDOUT/ERR is used
define	PROMPT		Memi[$1+9]		# prompt flag
define	QUIET		Memi[$1+10]		# quiet flag

define	RGIN		Memi[$1+11]		# lines specified
define	RGFIT		Memi[$1+12]		# all lines to fit
define	RGREFIT		Memi[$1+13]		# those to fit again
define	RGINB		Memi[$1+14]		# bands specified
define	RGFITB		Memi[$1+15]		# all bands to fit
define	RGREFITB	Memi[$1+16]		# those to fit again

define	NLOGFD		Memi[$1+17]		# number of logfiles
define	LOGFD		Memi[$1+18]		# array of logfiles

define	IC		Memi[$1+19]		# current ic descriptor
define	YMAX		Memi[$1+20]		# max number of lines
define	BMAX		Memi[$1+21]		# max number of lines
define	IC_DESC		Memi[$1+SFT_OFF+($3-1)*YMAX($1)+$2-1]	# ic descriptors


# T_SFIT -- Entry point for the task.  Read parameters,
# initialize structures and loop over the image templates.

procedure t_sfit ()

pointer	listin, listout, input, output, graphics
pointer	sf, gp, gt, in, out, mw, sh, sp
int	stat

int	sft_icfit(), imtgetim(), gt_init(), imtlen()
bool	clgetb()
pointer	imtopenp()

begin
	call smark (sp)
	call salloc (input, SZ_FNAME, TY_CHAR)
	call salloc (output, SZ_FNAME, TY_CHAR)
	call salloc (graphics, SZ_FNAME, TY_CHAR)

	# Open the image templates
	listin = imtopenp ("input")

	if (clgetb ("listonly"))
	    listout = NULL
	else {
	    listout = imtopenp ("output")
	    if (imtlen (listin) != imtlen (listout)) {
		call imtclose (listin)
		call imtclose (listout)
		call sfree (sp)
		call error (1, "Input and output image lists do not match")
	    }
	}

	# Initialize the various descriptors
	iferr (call sft_init (listin, listout, sf)) {
	    call imtclose (listin)
	    if (listout != NULL)
		call imtclose (listout)
	    call sfree (sp)
	    call erract (EA_ERROR)
	}

	# The graphics pointers are passed explicitly
	if (INTERACTIVE(sf) == YES) {
	    call clgstr ("graphics", Memc[graphics], SZ_FNAME)
	    gt = gt_init()
	    call gt_sets (gt, GTTYPE, "line")
	}

	# Fit the lines in each input image.

	while (imtgetim (listin, Memc[input], SZ_FNAME) != EOF) {

	    if (listout != NULL)
		stat = imtgetim (listout, Memc[output], SZ_FNAME)
	    else
		call strcpy (Memc[input], Memc[output], SZ_FNAME)

	    iferr {
		call sft_immap (Memc[input], Memc[output],
		    in, out, mw, sh, sf, gp)
	    } then {
		call erract (EA_WARN)
		next
	    }

	    stat = sft_icfit (in, out, mw, sh, sf, gp, gt, Memc[graphics])

	    call sft_unmap (in, out, mw, sh, sf)

	    if (stat == EOF)
		break
	}

	if (INTERACTIVE(sf) == YES)
	    call gt_free (gt)
	if (GRAPH_OPEN(sf) == YES)
	    call gclose (gp)

	call sft_close (sf)
	call imtclose (listin)
	if (listout != NULL)
	    call imtclose (listout)
	call sfree (sp)
end


# SFT_INIT -- Initialize templates, ranges, logfiles, type, icfit descriptors.

procedure sft_init (listin, listout, sf)

pointer	listin, listout		#I Image template descriptors
pointer	sf			#I Pointer to task switches

pointer	input, output, im, sp, mw
int	ymax, bmax, i, j

real	clgetr()
bool	clgetb()
int	clgwrd(), clgeti(), btoi(), strlen()
int	rg_next(), imtgetim(), imaccess(), xt_logopen()
pointer	rg_ranges(), immap(), smw_openim()
errchk	immap, smw_openim

begin
	call smark (sp)
	call salloc (input, SZ_LINE, TY_CHAR)
	call salloc (output, SZ_FNAME, TY_CHAR)

	sf = NULL
	iferr {

	    # find the maximum number of lines and bands (spectra)
	    ymax = 0
	    bmax = 0

	    while (imtgetim (listin, Memc[input], SZ_LINE) != EOF)
		if (imaccess (Memc[input], READ_ONLY) == YES) {
		    im = immap (Memc[input], READ_ONLY, 0)
		    mw = smw_openim (im)
		    ymax = max (SMW_LLEN(mw,2), ymax)
		    bmax = max (SMW_LLEN(mw,3), bmax)
		    call smw_close (mw)
		    call imunmap (im)
		}
	    call imtrew (listin)

	    if (listout != NULL) {
		while (imtgetim (listout, Memc[output], SZ_FNAME) != EOF)
		    if (imaccess (Memc[output], READ_ONLY) == YES) {
			im = immap (Memc[output], READ_ONLY, 0)
			mw = smw_openim (im)
			ymax = max (SMW_LLEN(mw,2), ymax)
			bmax = max (SMW_LLEN(mw,3), bmax)
			call smw_close (mw)
			call imunmap (im)
		    }
		call imtrew (listout)
	    }

	    # allocate space for the task switch structure
	    call malloc (sf, SFT_OFF + ymax * bmax, TY_STRUCT)

	    YMAX(sf) = ymax
	    BMAX(sf) = bmax

	    # NULL the pointers for error handling
	    RGIN(sf)	= NULL
	    RGINB(sf)	= NULL
	    NLOGFD(sf)	= 0
	    do j = 1, BMAX(sf)
		do i = 1, YMAX(sf)
		    IC_DESC(sf,i,j) = NULL

	    # Set the switches
	    INTERACTIVE(sf) = btoi (clgetb ("interactive"))
	    REPLACE(sf) = btoi (clgetb ("replace"))
	    WAVESCALE(sf) = btoi (clgetb ("wavescale"))
	    LOGSCALE(sf) = btoi (clgetb ("logscale"))
	    OVERRIDE(sf) = btoi (clgetb ("override"))
	    LISTONLY(sf) = btoi (clgetb ("listonly"))
	    GRAPH_OPEN(sf) = NO
	    PROMPT(sf) = INTERACTIVE(sf)
	    QUIET(sf) = btoi (INTERACTIVE(sf) == NO)

	    # Expand the range specification, allow either hyphens or colons

	    call clgstr ("lines", Memc[input], SZ_LINE)
	    do i = 1, strlen (Memc[input])
		if (Memc[input+i-1] == '-')
		    Memc[input+i-1] =  ':'
		else if (Memc[input+i-1] == 'x' || Memc[input+i-1] == 'X')
		    call error (1, "Range step (`x' notation) not implemented")

	    RGIN(sf) = rg_ranges (Memc[input], 1, YMAX(sf))
	    call rg_order (RGIN(sf))
	    call rg_merge (RGIN(sf))

	    call clgstr ("bands", Memc[input], SZ_LINE)
	    do i = 1, strlen (Memc[input])
		if (Memc[input+i-1] == '-')
		    Memc[input+i-1] =  ':'
		else if (Memc[input+i-1] == 'x' || Memc[input+i-1] == 'X')
		    call error (1, "Range step (`x' notation) not implemented")

	    RGINB(sf) = rg_ranges (Memc[input], 1, BMAX(sf))
	    call rg_order (RGINB(sf))
	    call rg_merge (RGINB(sf))

	    i = 0
	    j = 0
	    if (rg_next (RGIN(sf), i) == EOF || rg_next (RGINB(sf), j) == EOF)
		call error (1, "With range specification for `lines or bands'")
	    else {
		# Open the initial icfit descriptor
		call ic_open (IC(sf))

		call clgstr ("sample", Memc[input], SZ_LINE)
		call ic_pstr (IC(sf), "sample", Memc[input])
		call clgstr ("function", Memc[input], SZ_LINE)
		call ic_pstr (IC(sf), "function", Memc[input])

		call ic_puti (IC(sf), "naverage", clgeti ("naverage"))
		call ic_puti (IC(sf), "order", clgeti ("order"))
		call ic_putr (IC(sf), "low", clgetr ("low_reject"))
		call ic_putr (IC(sf), "high", clgetr ("high_reject"))
		call ic_puti (IC(sf), "niterate", clgeti ("niterate"))
		call ic_putr (IC(sf), "grow", clgetr ("grow"))
		call ic_puti (IC(sf), "markrej", btoi (clgetb ("markrej")))

		IC_DESC(sf,i,j) = IC(sf)
	    }

	    # Get the desired output type
	    OUTTYPE(sf) = clgwrd ("type", Memc[input], SZ_LINE, OUT_TYPES)

	    # Open the logfiles
	    NLOGFD(sf) = xt_logopen ("logfiles", "SFIT:", LOGFD(sf),
		LOG_TO_STDOUT(sf))

	} then {
	    call sfree (sp)
	    call sft_close (sf)
	    call erract (EA_ERROR)
	}

	call sfree (sp)
	return
end


# SFT_CLOSE -- Close the various descriptors.

procedure sft_close (sf)

pointer	sf			#I Pointer to task switches

int	i, j

begin
	if (sf != NULL) {
	    if (RGIN(sf) != NULL)
		call rg_free (RGIN(sf))
	    if (RGINB(sf) != NULL)
		call rg_free (RGINB(sf))
	    if (NLOGFD(sf) != 0)
		call xt_logclose (LOGFD(sf), NLOGFD(sf), "END:")
	    do j = 1, BMAX(sf)
		do i = 1, YMAX(sf)
		    if (IC_DESC(sf,i,j) != NULL)
			call ic_closer (IC_DESC(sf,i,j))
	    call mfree (sf, TY_STRUCT)
	}
end


# SFT_IMMAP -- Map images for sfit.

procedure sft_immap (input, output, in, out, mw, sh, sf, gp)

char	input[ARB]		#I Input image name
char	output[ARB]		#I Output image name
pointer	in, out			#O IMIO pointers
pointer	mw			#O MWCS pointer
pointer	sh			#O SHDR pointer
pointer	sf			#I Pointer for task switches
pointer	gp			#I GIO pointer

int	i, ax1, ax2, ax3
pointer	inroot, insect, outroot, outsect, b1, b2
pointer	sp, inranges, outranges
pointer	rgin, rgout, rgtmp, rgtmpb
long	v1[IM_MAXDIM], v2[IM_MAXDIM]
char	emsg[SZ_LINE]

int	imaccess(), imaccf(), imgnlr(), impnlr(), strcmp()
pointer	immap(), smw_openim()
pointer	rg_ranges(), rg_window(), rg_union(), rg_intersect()
errchk	immap, smw_openim

define	err_	13

begin
	call smark (sp)
	call salloc (inroot, SZ_FNAME, TY_CHAR)
	call salloc (insect, SZ_FNAME, TY_CHAR)
	call salloc (outroot, SZ_FNAME, TY_CHAR)
	call salloc (outsect, SZ_FNAME, TY_CHAR)
	call salloc (inranges, SZ_LINE, TY_CHAR)
	call salloc (outranges, SZ_LINE, TY_CHAR)

	in = NULL
	out = NULL
	mw = NULL
	sh = NULL
	RGFIT(sf) = NULL
	RGREFIT(sf) = NULL
	RGFITB(sf) = NULL
	RGREFITB(sf) = NULL

	call imgimage (input, Memc[inroot], SZ_FNAME)
	call imgsection (input, Memc[insect], SZ_FNAME)

	call imgimage (output, Memc[outroot], SZ_FNAME)
	call imgsection (output, Memc[outsect], SZ_FNAME)

	if (Memc[insect] != EOS || Memc[outsect] != EOS) {

	    call sprintf (emsg, SZ_LINE, "Sections not allowed (%s --> %s)")
		call pargstr (input)
		call pargstr (output)
	    goto err_

	} else if (imaccess (Memc[inroot], READ_ONLY) == NO) {

	    call sprintf (emsg, SZ_LINE, "Cannot access %s")
		call pargstr (input)
	    goto err_

	} else if (LISTONLY(sf) == YES) {

	    # The `out = in' allows the ranges code at the end of this
	    # procedure to cover all cases (with a little inefficiency).
	    # No check on the sizes of the input and output images.

	    in = immap (Memc[inroot], READ_ONLY, 0)
	    out = in

	} else if (strcmp (Memc[inroot], Memc[outroot]) == 0) {

	    # Overwrite the input image.
	    in = immap (Memc[inroot], READ_WRITE, 0)
	    out = in

	} else if (imaccess (Memc[outroot], READ_WRITE) == NO) {

	    in = immap (Memc[inroot], READ_ONLY, 0)
	    out = immap (Memc[outroot], NEW_COPY, in)
	    if (IM_PIXTYPE(out) != TY_DOUBLE)
		IM_PIXTYPE(out) = TY_REAL

	    # Do this since imcopy is unimplemented

	    call amovkl (long(1), v1, IM_MAXDIM)
	    call amovkl (long(1), v2, IM_MAXDIM)

	    while (imgnlr (in, b1, v1) != EOF && impnlr (out, b2, v2) != EOF)
		call amovr (Memr[b1], Memr[b2], IM_LEN(in, 1))

	} else {

	    in = immap (Memc[inroot], READ_ONLY, 0)
	    out = immap (Memc[outroot], READ_WRITE, 0)

	    # This relies on the axes beyond IM_NDIM(im) being unity

	    do i = 1, max (IM_NDIM(in), IM_NDIM(out))
		if (IM_LEN(in, i) != IM_LEN(out, i)) {
		    call sprintf (emsg, SZ_LINE, "%s & %s aren't the same size")
			call pargstr (Memc[inroot])
			call pargstr (Memc[outroot])
		    goto err_
		}

	}

	do i = 4, IM_NDIM(in)
	    if (IM_LEN(in, i) != 1) {
		call sprintf (emsg, SZ_LINE, "Too many dimensions for %s")
		    call pargstr (Memc[inroot])
		goto err_
	    }

	if (imaccf (in, SFT_KW) == YES)
	    call imgstr (in, SFT_KW, Memc[inranges], SZ_LINE)
	else
	    call strcpy ("", Memc[inranges], SZ_LINE)

	if (imaccf (out, SFT_KW) == YES)
	    call imgstr (out, SFT_KW, Memc[outranges], SZ_LINE)
	else {
	    call strcpy ("", Memc[outranges], SZ_LINE)
	    call imastr (out, SFT_KW, Memc[outranges])
	}

	mw = smw_openim (in)
	ax1 = SMW_LLEN(mw,1)
	ax2 = SMW_LLEN(mw,2)
	ax3 = SMW_LLEN(mw,3)

	rgin = rg_ranges (Memc[inranges], 1, ax2)
	rgout = rg_ranges (Memc[outranges], 1, ax2)
	rgtmp = rg_union (rgin, rgout)
	call rg_free (rgin)
	call rg_free (rgout)

	if (imaccf (in, SFT_KWB) == YES)
	    call imgstr (in, SFT_KWB, Memc[inranges], SZ_LINE)
	else
	    call strcpy ("", Memc[inranges], SZ_LINE)

	if (imaccf (out, SFT_KWB) == YES)
	    call imgstr (out, SFT_KWB, Memc[outranges], SZ_LINE)
	else {
	    call strcpy ("", Memc[outranges], SZ_LINE)
	    call imastr (out, SFT_KWB, Memc[outranges])
	}

	rgin = rg_ranges (Memc[inranges], 1, ax3)
	rgout = rg_ranges (Memc[outranges], 1, ax3)
	rgtmpb = rg_union (rgin, rgout)
	call rg_free (rgin)
	call rg_free (rgout)

	if (OVERRIDE(sf) == YES) {
	    RGFIT(sf) = rg_window (RGIN(sf), 1, ax2)
	    RGREFIT(sf) = rgtmp
	    RGFITB(sf) = rg_window (RGINB(sf), 1, ax3)
	    RGREFITB(sf) = rgtmpb
	} else {
	    call rg_inverse (rgtmp, 1, ax2)
	    RGFIT(sf) = rg_intersect (RGIN(sf), rgtmp)
	    RGREFIT(sf) = rg_ranges ("0", 1, 2)
	    call rg_free (rgtmp)
	    #call rg_inverse (rgtmpb, 1, ax3)
	    #RGFITB(sf) = rg_intersect (RGINB(sf), rgtmpb)
	    #RGREFITB(sf) = rg_ranges ("0", 1, 2)
	    #call rg_free (rgtmpb)
	    RGFITB(sf) = rg_window (RGINB(sf), 1, ax3)
	    RGREFITB(sf) = rgtmpb
	}

	if (RG_NPTS(RGFIT(sf)) <= 0) {
	    call sprintf (emsg, SZ_LINE, "No lines left to fit for %s")
		call pargstr (Memc[inroot])
	    goto err_
	}

	call sfree (sp)
	return

err_	call sfree (sp)
	call sft_unmap (in, out, mw, sh, sf)
	if (GRAPH_OPEN(sf) == YES) {
	    call gclose (gp)
	    GRAPH_OPEN(sf) = NO
	}
	# STDERR should get flushed AFTER closing graphics
	call error (1, emsg)
end


# SFT_UNMAP -- Unmap images for sfit.

procedure sft_unmap (in, out, mw, sh, sf)

pointer	in, out			#I IMIO pointers
pointer	mw			#I MWCS pointer
pointer	sh			#I SHDR pointer
pointer	sf			#I Task structure pointer

begin
	call shdr_close (sh)
	if (mw != NULL)
	    call smw_close (mw)
	if (out != NULL && out != in)
	    call imunmap (out)
	if (in != NULL)
	    call imunmap (in)
	if (RGFIT(sf) != NULL)
	    call rg_free (RGFIT(sf))
	if (RGREFIT(sf) != NULL)
	    call rg_free (RGREFIT(sf))
	if (RGFITB(sf) != NULL)
	    call rg_free (RGFITB(sf))
	if (RGREFITB(sf) != NULL)
	    call rg_free (RGREFITB(sf))
end


# SFT_ICFIT -- Given the image descriptors determine the fitting function
# for each line and output the fit, difference, ratio or coefficients.

int procedure sft_icfit (in, out, mw, sh, sf, gp, gt, graphics)

pointer	in, out				#I IMIO pointers
pointer	mw				#I MWCS pointer
pointer	sh				#I SHDR pointer
pointer	sf				#I Pointer for task switches
pointer	gp				#I GIO pointer
pointer	gt				#I GTOOLS pointer
char	graphics[ARB]			#I Graphics device

pointer	sp, wts, cv, data
int	line, band, i, j, n

int	sft_getline()
pointer	gopen(), imps3r()
real	sft_efncr()
extern	sft_efncr

begin
	call smark (sp)
	call salloc (wts, SMW_LLEN(mw,1), TY_REAL)

	line = 0
	band = 0
	while (sft_getline (in, mw, sh, sf, gt, line, band) != EOF) {

	    call amovkr (1., Memr[wts], SN(sh))

	    if (QUIET(sf) == NO) {
		if (GRAPH_OPEN(sf) == NO) {
		    gp = gopen (graphics, NEW_FILE, STDGRAPH)
		    GRAPH_OPEN(sf) = YES
		}
		call icg_fit (IC(sf), gp, "cursor", gt, cv, Memr[SX(sh)],
		    Memr[SY(sh)], Memr[wts], SN(sh))
	    } else
		call ic_fit (IC(sf), cv, Memr[SX(sh)], Memr[SY(sh)],
		    Memr[wts], SN(sh), YES, YES, YES, YES)

	    if (LISTONLY(sf) == NO) {
		i = LINDEX(sh,1)
		j = LINDEX(sh,2)
		n = SMW_LLEN(mw,1)
		switch (SMW_LAXIS(mw,1)) {
		case 1:
		    data = imps3r (out, 1, n, i, i, j, j)
		case 2:
		    data = imps3r (out, i, i, 1, n, j, j)
		case 3:
		    data = imps3r (out, i, i, j, j,  1, n)
		}
		if (SN(sh) < n)
		    call aclrr (Memr[data], n)

		switch (OUTTYPE(sf)) {
		case DATA:
		    if (REPLACE(sf) == YES)
			call ic_clean (IC(sf), cv, Memr[SX(sh)], Memr[SY(sh)],
			    Memr[wts], SN(sh))
		    call amovr (Memr[SY(sh)], Memr[data], SN(sh))
		    call sft_update (out, mw, line, band)
		case FIT:
		    call cvvector (cv, Memr[SX(sh)], Memr[data], SN(sh))
		    call sft_update (out, mw, line, band)
		case DIFFERENCE:
		    call cvvector (cv, Memr[SX(sh)], Memr[data], SN(sh))
		    if (REPLACE(sf) == YES)
			call ic_clean (IC(sf), cv, Memr[SX(sh)], Memr[SY(sh)],
			    Memr[wts], SN(sh))
		    call asubr (Memr[SY(sh)], Memr[data], Memr[data], SN(sh))
		    call sft_update (out, mw, line, band)
		case RATIO:
		    call cvvector (cv, Memr[SX(sh)], Memr[data], SN(sh))
		    if (REPLACE(sf) == YES)
			call ic_clean (IC(sf), cv, Memr[SX(sh)], Memr[SY(sh)],
			    Memr[wts], SN(sh))
		    call advzr (Memr[SY(sh)], Memr[data], Memr[data], SN(sh),
			sft_efncr)
		    call sft_update (out, mw, line, band)
		default:
		    call error (1, "bad switch in sft_icfit")
		}
	    }

	    call sft_power (in, line, cv, gp, sf)
	    call cvfree (cv)

	}

	# This terminates the cursor (GIN) mode echoplex suppression in
	# case the next sft_immap generates a password prompt from ZFIOKS.
	# Note that any such password prompt (from the kernel!) will
	# now show up on the status line, not the graphics plane.

	if (GRAPH_OPEN(sf) == YES) {
	    call printf ("\r")
	    call flush (STDOUT)
	}

	call sfree (sp)
	return (line)
end


# SFT_GETLINE -- Get image data to be fit.  Returns the line and band numbers.
# Returns EOF when done.

int procedure sft_getline (in, mw, sh, sf, gt, line, band)

pointer	in			#I IMIO pointer
pointer	mw			#I MWCS pointer
pointer	sh			#I SHDR pointer
pointer	sf			#I Pointer for task switches
pointer	gt			#I GTOOLS pointer
int	line			#U Line number
int	band			#U Band number

int	i
bool	waveok
char	ask[LEN_ANS]
pointer	linebuf, rg1, rg2, sp

int	clgwrd(), rg_next(), rg_inrange()
pointer	rg_ranges(), rg_intersect()
real	sft_efncr()
extern	sft_efncr
errchk	shdr_open

define	again_		99

begin
	call smark (sp)
	call salloc (linebuf, SZ_LINE, TY_CHAR)

	if (band == 0)
	    if (rg_next (RGFITB(sf), band) == EOF)
		return (EOF)

again_	if (rg_next (RGFIT(sf), line) == EOF) {
	    line = 0
	    if (rg_next (RGFITB(sf), band) == EOF)
		return (EOF)
	    goto again_
	}

	if (PROMPT(sf) == YES) {
	    call clprintf ("ask.p_min", "%s")
		call pargstr (SFT_ANS1X)

	    if (rg_inrange (RGREFIT(sf), line) == YES &&
		rg_inrange (RGREFITB(sf), band) == YES) {
		call clprintf ("ask.p_prompt",
		    "Refit [%d,%d] of %s w/ graph?        ")
	    } else {
		call clprintf ("ask.p_prompt",
		    "Fit [%d,%d] of %s w/ graph?          ")
	    }
	    call pargi (line)
	    call pargi (band)
	    call pargstr (IM_HDRFILE(in))

	    switch (clgwrd ("ask", ask, LEN_ANS, SFT_ANS1)) {

	    case YES_ONCE:
		QUIET(sf) = NO

	    case NO_ONCE:
		QUIET(sf) = YES

	    case SKIP_ONCE:
		goto again_

	    case YES_ALWAYS:
		QUIET(sf) = NO
		PROMPT(sf) = NO

	    case NO_ALWAYS:
		QUIET(sf) = YES
		PROMPT(sf) = NO

	    case SKIP_ALWAYS:
		call clprintf ("ask", "cancel")
		call clprintf ("ask.p_min", "%s")
		    call pargstr (SFT_ANS2X)
		call clprintf ("ask.p_prompt",
		    "Skip what?    (`all' to exit task)   ")

		switch (clgwrd ("ask", ask, LEN_ANS, SFT_ANS2)) {

		case SKIP_SPEC:
		    call clprintf ("ask", "yes")
		    # delete the spectrum from the list
		    call sprintf (Memc[linebuf], SZ_LINE, "%d")
			call pargi (line)

		    rg1 = rg_ranges (Memc[linebuf], 1, SMW_LLEN(mw,2))
		    call rg_inverse (rg1, 1, SMW_LLEN(mw,2))
		    rg2 = rg_intersect (RGIN(sf), rg1)
		    call rg_free (rg1)
		    call rg_free (RGIN(sf))

		    RGIN(sf) = rg2
		    goto again_

		case SKIP_IMAGE:
		    call clprintf ("ask", "yes")
		    return (EOF)

		case SKIP_ALL:
		    call clprintf ("ask", "yes")
		    return (EOF)

		case SKIP_CANCEL:
		    call clprintf ("ask", "yes")
		    line = line - 1
		    goto again_

		default:
		    call error (1, "bad switch (2) in sft_getline")

		}

	    default:
		call error (1, "bad switch (1) in sft_getline")

	    }

	}

	call shdr_open (in, mw, line, band, INDEFI, SHDATA, sh)

	if (LOGSCALE(sf) == YES)
	    call alogr (Memr[SY(sh)], Memr[SY(sh)], SN(sh), sft_efncr)

	if (WAVESCALE(sf) == YES) {
	    waveok = true
	} else
	    waveok = false

	if (!waveok)
	    do i = 1, SN(sh)
		Memr[SX(sh)+i-1] = i

	if (LOGSCALE(sf) == YES)
	    call alogr (Memr[SX(sh)], Memr[SX(sh)], SN(sh), sft_efncr)

	# Initialize and/or update the icfit descriptor

	if (IC_DESC(sf,line,band) == NULL) {
	    call ic_open (IC_DESC(sf,line,band))
	    call ic_copy (IC(sf), IC_DESC(sf,line,band))
	    #call ic_pstr (IC_DESC(sf,line,band), "sample", "*")
	}

	IC(sf) = IC_DESC(sf,line,band)

	call ic_putr (IC(sf), "xmin", min (Memr[SX(sh)], Memr[SX(sh)+SN(sh)-1]))
	call ic_putr (IC(sf), "xmax", max (Memr[SX(sh)], Memr[SX(sh)+SN(sh)-1]))

	if (QUIET(sf) == NO) {
	    if (waveok && LOGSCALE(sf) == YES) {
		call ic_pstr (IC(sf), "xlabel", "log wavelength")
		call ic_pstr (IC(sf), "ylabel", "log data")
	    } else if (LOGSCALE(sf) == YES) {
		call ic_pstr (IC(sf), "xlabel", "log column")
		call ic_pstr (IC(sf), "ylabel", "log data")
	    } else if (waveok) {
		call ic_pstr (IC(sf), "xlabel", "wavelength")
		call ic_pstr (IC(sf), "ylabel", "")
	    } else {
		call ic_pstr (IC(sf), "xlabel", "column")
		call ic_pstr (IC(sf), "ylabel", "")
	    }

	    call sprintf (Memc[linebuf], SZ_LINE, "%s, [%d,%d]\n%s")
		call pargstr (IM_HDRFILE(in))
		call pargi (line)
		call pargi (band)
		call pargstr (TITLE(sh))

	    call gt_sets (gt, GTTITLE, Memc[linebuf])
	}

	call sfree (sp)
	return (OK)
end


# SFT_EFNCR -- Called by advzr on division by zero or by alogr for a
# zero or negative argument.

real procedure sft_efncr (x)

real	x

begin
	return (0.)
end


# SFT_POWER -- Transform the curfit output into a power series and
# print the coefficients to the logfiles.  This should be modified to
# print the errors as well.  That requires modifying the curfit routine
# cvpower to deal with errors; and adding an icfit routine (or include
# file define) that allows access to the dynamic arrays of sample points
# that are initialized if the sample is less than the whole set of points.

procedure sft_power (im, line, cv, gp, sf)

pointer	im			#I IMIO descriptor for labeling
int	line			#I Image line number for labeling
pointer	cv			#I CURFIT pointer
pointer	gp			#I GIO pointer for tidy output
pointer sf			#I Pointer for task switches

pointer	ps_coeff, linebuf, sp
int	ncoeffs, i, j, fd

int	cvstati(), strcmp()

begin
	if (NLOGFD(sf) <= 0)
	    return

	call smark (sp)
	call salloc (linebuf, SZ_LINE, TY_CHAR)

	# cvpower only works with legendre or chebyshev functions

	call ic_gstr (IC(sf), "function", Memc[linebuf], SZ_LINE)
	if (strcmp (Memc[linebuf], "legendre") != 0 &&
	    strcmp (Memc[linebuf], "chebyshev") != 0) {
	    call sfree (sp)
	    return
	}

	if (GRAPH_OPEN(sf) == YES && LOG_TO_STDOUT(sf) == YES) {
	    call gclose (gp)
	    GRAPH_OPEN(sf) = NO
	}

	ncoeffs = cvstati (cv, CVNCOEFF)
	call salloc (ps_coeff, ncoeffs, TY_REAL)
	call cvpower (cv, Memr[ps_coeff], ncoeffs)

	do i = 1, NLOGFD(sf) {
	    fd = Memi[LOGFD(sf)+i-1]

	    call fprintf (fd, "Line %d of %s:\n\n")
		call pargi (line)
		call pargstr (IM_HDRFILE(im))

	    call fprintf (fd, "      coeff           value\n")

	    do j = 1, ncoeffs {
		call fprintf (fd, "\t%d\t%12.5e\n")
		    call pargi (j)
		    call pargr (Memr[ps_coeff+j-1])
	    }

	    call fprintf (fd, "\n")
	    call flush (fd)
	}

	call sfree (sp)
end


# SFT_UPDATE -- Update the keyword with completed spectrum.  Flush the pixels.

procedure sft_update (im, mw, line, band)

pointer	im			#I IMIO pointer
pointer	mw			#I MWCS pointer
int	line			#I Line just completed
int	band			#I Band just completed

pointer linebuf, rg1, rg2, rgold, sp

pointer	rg_ranges(), rg_union()

begin
	call smark (sp)
	call salloc (linebuf, SZ_LINE, TY_CHAR)

	# this could be recoded to use "rg_add"

	call sprintf (Memc[linebuf], SZ_LINE, "%d")
	    call pargi (line)
	rg1 = rg_ranges (Memc[linebuf], 1, SMW_LLEN(mw,2))

	call imgstr (im, SFT_KW, Memc[linebuf], SZ_LINE)
	rg2 = rg_ranges (Memc[linebuf], 1, SMW_LLEN(mw,2))

	rgold = rg_union (rg1, rg2)
	call rg_encode (rgold, Memc[linebuf], SZ_LINE)
	call impstr (im, SFT_KW, Memc[linebuf])

	call rg_free (rg1)
	call rg_free (rg2)
	call rg_free (rgold)

	call sprintf (Memc[linebuf], SZ_LINE, "%d")
	    call pargi (band)
	rg1 = rg_ranges (Memc[linebuf], 1, SMW_LLEN(mw,3))

	call imgstr (im, SFT_KWB, Memc[linebuf], SZ_LINE)
	rg2 = rg_ranges (Memc[linebuf], 1, SMW_LLEN(mw,3))

	rgold = rg_union (rg1, rg2)
	call rg_encode (rgold, Memc[linebuf], SZ_LINE)
	call impstr (im, SFT_KWB, Memc[linebuf])

	call rg_free (rg1)
	call rg_free (rg2)
	call rg_free (rgold)

	call imflush (im)
	call sfree (sp)
end