#Flat-fielding and badpix rejection
imdel tmp0,tmp1,mask,mask2,FMSAfilenom.fits,FMSAfilenom_bpm.fits
imcopy FMSAfileno tmp0.fits
#Cross talk subtraction
rmcross tmp0.fits tmp0.fits
###Stripe pattern subtraction
#rmstripe1 tmp0.fits tmp0.fits
#rmstripe2 tmp0.fits tmp0.fits
###Quadrant level adjustment
quadlev tmp0.fits tmp0.fits
###
imarith tmp0.fits / ../flat tmp0.fits
displ tmp0 1 zs+
median tmp0 tmp1 3 3
imarith tmp0 - tmp1 tmp1
imarith tmp1 * ../badpixr tmp1
imfunc tmp1 tmp1 abs
imrepl tmp1 65000. upper=INDEF lower=65000.
!rm tmp.tbl tmp1.tbl
imhist tmp1 z1=-50 z2=65050 binwidt=100 nbins=651 hist_type=cumulative listout+ > tmp.tbl
###Number of rejected bad pixels with high count.
###(If you want to apply this script to a raw image, use upper line.)
#!../thresh tmp.tbl 1300 tmp1 > tmp1.tbl
!../thresh tmp.tbl 300 tmp1 > tmp1.tbl
cl < tmp1.tbl
imstati tmp1 lower=INDEF upper=0.5
imarith ../badpixr * tmp1 mask.fits
convolve mask.fits mask.fits "0. 0.2 0.; 0.2 0.2 0.2; 0. 0.2 0."
imrepl mask 0. lower=INDEF upper=0.9
displ mask 2 zs- zr- z1=1 z2=0
imcopy mask FMSAfilenom_bpm.fits
imstati mask lower=INDEF upper=0.5
imcopy ../badpix2r mask2.fits
!../fixbadpix tmp0.fits FMSAfilenom.fits
displ FMSAfilenom 3 zs+

#Deformation and extract spectra
imdel FMSAfilenoe.fits,FMSAfilenos.fits,FMSAfilenoa.fits,FMSAfilenox.fits,check,bkg,FMSAfilenoe_bpm.fits,FMSAfilenos_bpm.fits,FMSAfilenoa_bpm.fits
!echo "0.5 1 1 1 1 1 1 1 0.5" > extract.dat
!../extract FMSAfilenom.fits FMSAfilenoe.fits irs1_cont_BANDe.dat SHIFT
displ check 4 zs+
displ FMSAfilenoe 5 zs+
median bkg bkg 27 9
!../extract2 bkg.fits bkg.fits
magnify bkg bkg 1. 25. y1=1.01 y2=9.0 interpo=linear boundar=nearest fluxcon-
displ bkg 6 zs+
imarith FMSAfilenoe.fits - bkg FMSAfilenos.fits
displ FMSAfilenos 7 zs+
imrename FMSAfilenoe_bpm.fits FMSAfilenos_bpm.fits
!../align FMSAfilenos.fits FMSAfilenoa.fits irs1_cont_BANDa.dat
#!../align FMSAfilenoe.fits FMSAfilenoa.fits irs1_cont_BANDa.dat
displ FMSAfilenoa 8 zs+
imdel tmp1
imarith FMSAfilenoa / irs1_cont_BANDa tmp1
fit1d tmp1 tmp1 difference axis=2 inter- function=spline3 order=10 high_reject=3 low_reject=3 niterate=10 grow=0
imarith tmp1 * irs1_cont_BANDa FMSAfilenox.fits
### If the cont image is not good, use this line instead of above three lines.
#fit1d FMSAfilenoa FMSAfilenox.fits difference axis=2 inter- function=spline3 order=10 high_reject=3 low_reject=3 niterate=10 grow=0
displ FMSAfilenox 9 zs+
