pro negative_persistance_plot,dir=dir,fitsfilename=fitsfilename
cd, dir
xwindow=[800,850]
ywindow=[240,290]
xrefwin=[800,850]
yrefwin=[300,350]
stop
xwinsize=xwindow(1)-xwindow(0)
ywinsize=ywindow(1)-ywindow(0)
xrefwinsize=xrefwin(1)-xrefwin(0)
yrefwinsize=yrefwin(1)-yrefwin(0)

im=(readfits(fitsfilename,h)-65535)

windowimage=fltarr(xrefwinsize,yrefwinsize)
refwinimage=fltarr(xrefwinsize,yrefwinsize)

windowimage=im(xwindow(0):xwindow(1),ywindow(0):ywindow(1))
refwinimage=im(xrefwin(0):xrefwin(1),yrefwin(0):yrefwin(1))

sumwin=total(windowimage)
numpix=xwinsize*ywinsize
avgwin=sumwin/numpix
avgstring='Average of Neg Persistance window: ' + strtrim(avgwin,2)
windowstring='Window: ' +'['+strtrim(xwindow(0),2)+':'+strtrim(xwindow(1),2)+','+strtrim(ywindow(0),2)+':'+strtrim(ywindow(1),2)+']'
print,avgstring

sumrefwin=total(refwinimage)
numrefpix=xrefwinsize*yrefwinsize
avgrefwin=sumrefwin/numrefpix
avgrefstring='Average of reference window: ' + strtrim(avgrefwin,2)
refwinstring='Reference Window: ' +'['+strtrim(xrefwin(0),2)+':'+strtrim(xrefwin(1),2)+','+strtrim(yrefwin(0),2)+':'+strtrim(yrefwin(1),2)+']'
print,avgrefstring

set_plot,'win'
surface,windowimage,charsize=3,/lego,ztitle='signal'
set_plot,'ps'
filename = fitsfilename+'_'+strtrim(xwindow(0),2)+','+strtrim(ywindow(0),2)+'_Negative_Persistance_Plot.ps'
device, filename =filename,/landscape
!p.font = -1    ; use vector fonts for PS
!P.MULTI = 0    ; Set up for one plot per page
fsub = dir+path_sep()+filename   ; set text to print at bottom of plot

; set some size values
asize = 1.3    ; charsize of annotations
athick = 4.0    ; charthick of annotations
lthick = 8.0    ; line thickness
!x.thick=lthick
!y.thick=lthick
!z.thick=lthick

surface,windowimage,charsize=asize*2,/lego,ztitle='signal',thick=lthick,charthick=athick,xtitle='x pixel',ytitle='y pixel'
; Add labels & fitted line
; write the file name outside the margin of the plot
black=0
xyouts, 1.0, 0, fsub, charsize = asize*0.75, charthick = athick, color = black, /device
xyouts, 1.0, 1200, avgrefstring, charsize = asize*0.75, charthick = athick, color = black, /device
xyouts, 1.0, 1600, avgstring, charsize = asize*0.75, charthick = athick, color = black, /device
xyouts, 1.0, 800, windowstring, charsize = asize*0.75, charthick = athick, color = black, /device
xyouts, 1.0, 400, refwinstring, charsize = asize*0.75, charthick = athick, color = black, /device
device,/close

end