function rqe_makeflats,filter,tall,mm

;
; jflats=rqe_makeflats('J+PK50-2',jtemps,jmed)
;

fon=findfile('*'+filter+'*_On*.fits')
foff=findfile('*'+filter+'*_Off*.fits')

; start of loop   ****************************************************************
non=n_elements(fon)
noff=n_elements(foff)

ton=fltarr(non)
toff=fltarr(noff)

for i=0,non-1 do ton(i)=float(strmid(fon(i),strpos(fon(i),'_On')-2,2))
for i=0,noff-1 do toff(i)=float(strmid(foff(i),strpos(foff(i),'_Off')-2,2))

prev=0
tall=0
for i=1,non-1 do begin
	if ton(i) ne prev then begin
		tall=[tall,ton(i)]
	endif
	prev=ton(i)
endfor
tall=tall(1:*)
ntemps=n_elements(tall)

fits_read,fon(0),t
sz=size(t)

onmed=fltarr(sz(1),sz(2),ntemps)
offmed=fltarr(sz(1),sz(2),ntemps)


print,'making median of ON images at each temp...'
for i=0,ntemps-1 do begin

	print,'Temp: ',tall(i)
	u=where(ton eq tall(i))

	if u(0) ne -1 then begin
		ss=fltarr(sz(1),sz(2),n_elements(u))
		print,'Readimg image #'
		for j=0,n_elements(u)-1 do begin
			print,j
			fits_read,fon(u(j)),t
			ss(*,*,j)=t(*,*,1)-float(t(*,*,0))
			; do ref pix sub here if desired
		endfor

		; if ge 3 then median
		if n_elements(u) ge 3 then for x=0,sz(1)-1 do for y=0,sz(2)-1 do onmed(x,y,i)=median(ss(x,y,*))

		; if only 2 then average
		if n_elements(u) eq 2 then onmed(*,*,i)=(onmed(*,*,i)+ss(*,*,0)+float(ss(*,*,1)))/2.

		; if only 1 then just use that image
		if n_elements(u) eq 1 then onmed(*,*,i)=ss(*,*,0)

		; otherwise there were none at this temp so leave as 0
	endif

endfor


print,'making median of OFF images at each temp...'
for i=0,ntemps-1 do begin

	print,'Temp: ',tall(i)
	u=where(toff eq tall(i))

	if u(0) ne -1 then begin
		ss=fltarr(sz(1),sz(2),n_elements(u))
		print,'Readimg image #'
		for j=0,n_elements(u)-1 do begin
			print,j
			fits_read,foff(u(j)),t
			ss(*,*,j)=t(*,*,1)-float(t(*,*,0))
			; do ref pix sub here if desired
		endfor

		; if ge 3 then median
		if n_elements(u) ge 3 then for x=0,sz(1)-1 do for y=0,sz(2)-1 do offmed(x,y,i)=median(ss(x,y,*))

		; if only 2 then average
		if n_elements(u) eq 2 then offmed(*,*,i)=(offmed(*,*,i)+ss(*,*,0)+float(ss(*,*,1)))/2.

		; if only 1 then just use that image
		if n_elements(u) eq 1 then offmed(*,*,i)=ss(*,*,0)

		; otherwise there were none at this temp so leave as 0
	endif

endfor

dif=onmed-offmed
mm=fltarr(ntemps)
for i=0,ntemps-1 do mm(i)=median(dif(100:1900,100:1900,i))
t=0
ss=0

; end of loop   ****************************************************************

return,dif

end
