pro maskgen,ntran,iwstrt,iwend,nwl,mask1,mask2

;  routine to generate mask functions for smoothly extending data
;  between lines and making the wavelength range periodic

;	INPUTS:
;	ntran	= number of wavelength points to transform (>maxsz),
;				i.e. for hinode, next power of 2 > 112 = 128
;	iwstrt	= array of start pixels for synthetic profiles [nline]
;	iwend	= array of end pixels for synthetic profiles [nline]
;	nwl	= number of spectral pixels in original data
;	nline	= number of spectral lines fit
;  THE FOLLOWING PARAMETERS ARE FOR SMEARING CONVOLUTION
;  THIS ROUTINE ASSUMES ALL LINES ARE APPROXIMATELY AT THE SAME
;  WAVELENGTH, AND THAT THE SMEARING FUNCTION IS THE SAME FOR
;  EACH LINE 
;
;	OUTPUTS:
;	mask1 = ascending wavelength array mask function [ntran,nline]
;	mask2 = descending wavelength array mask function [ntran,nline]

nline = n_elements(iwstrt)      ; number of computed spectral lines

;  define the mask arrays for extension
mask1 = fltarr(ntran,nline)
mask1(*,*) = 0.
mask2 = fltarr(ntran,nline)
mask2(*,*) = 0.

;  build the functions that extend the data smoothly and make it
;  periodic over the extended range to even power of 2 wavelength
;  pixels


;  first must smoothly extend the profiles between computed regimes
;  number of segments to fit = nline because the extension is periodic
;  first interpolation segment is between end point of final
;  line and start point of first line.  nmask = total number of
;  pixels, including end points, involved in the cosine function
nmask = ((ntran-1) - iwend(nline-1) +1) + (iwstrt(0) + 1)
amul = !pi/float(nmask-1)
;  build mask of this length starting at pixel 0, but does
;  not include the end points 0 or nmask-1.  This is the decending
;  factor starting with unity at the pixel 0 and descending
;  to zero at the pixel nmask-1
for ii = 1,nmask-2 do mask1(ii,0) =  0.5*(1. + cos(amul*float(ii)))
;  now shift this mask back to its original position
;  to wrap around end of sequence
mask1(*,0) = shift(mask1(*,0),iwend(nline-1))
;  find locations where mask1 = 0
whr = where(mask1(*,0) eq 0.)
;  find conjugate mask to build toward endpoints
mask2(*,0) = 1. - mask1(*,0)
mask2(whr,0) = 0.

;  build similar descending masks for each of the inter-line
;  intervals
for im = 1,nline-1 do begin
	mask1(*,im) = 0.
	mask2(*,im) = 0.
	nmask = iwstrt(im) - iwend(im-1) + 1
	amul = !pi/float(nmask-1)
	for ii = iwend(im-1)+1,iwstrt(im)-1 do begin
		mask1(ii,im) = 0.5*(1. + cos(amul*float(ii-iwend(im-1))))
	endfor
;  find locations where mask1 = 0
	whr = where(mask1(*,im) eq 0.)
;  build conjugate mask for endpoints
	mask2(*,im) = 1. - mask1(*,im)
	mask2(whr,im) = 0.
endfor

return
end
