pro mdi_display, restart=restart, qdisp_con=qdisp_con, nodiff=nodiff, qdebug=qdebug, $
			qcenter=qcenter, thresh=thresh
;+
;NAME:
;	mdi_display
;PURPOSE:
;	To display the images as they are received by the EGSE.
;	The executable "mdi_sci" is used to copy the telemetry data through
;	shared memory
;HISTORY:
;	Written 1993 by M.Levay (?)
;	21-Sep-94 (MDM) - Modified to use GET_DPC_INFO and a database
;			  file to get the data product information rather than
;			  case statements in the program
;			- Allow continuous display to the window as the
;			  data is assembled.
;			- Added a "-a" to the mdi_sci call if EGSE_VER is
;			  greater than or equal to 3.1
;			- Added /RESTART option
;			- Incorporated changes made in RC.PRO
;			- Added /QDISP_CON and /NODIFF
;	25-Oct-94 (RAC) - changed /retain=1 to /retain=2 (full backing store)
;			- Added /retain=2 to window,7 call that didn't have one
;       13-Apr-95 (DPM) - Created mdi_display3; Uses R0-R9 to obtain temperatures
;                         commented out Count and Page number display
;	14-Sep-95 (MDM) - Modified to show the CFFFFF25 and CFFFFF26 as croped images
;			- Fixed some bugs with undefined data products
;			- Added some info for displaying with the image
;			  (DPC, frame#)
;	15-Sep-95 (MDM) - Various other fixes/options
;	 9-Oct-95 (MDM) - Made some changes related to using the data product
;			  size as send down in the data product header
;			- Made several debug statements come out only when /QDEBUG
;			  is set
;	12-Oct-95 (MDM) - Modified the DPC table format (but all changes necessary
;			  should have been in GET_DPC_INFO)
;			- Modification to find the min/max of the crop region only,
;			  not the embedded image
;	13-Oct-95 (MDM) - Modified to use MK_DPC_IMAGE
;	17-Oct-95 (MDM) - Modification to rebin a 1024x1024 image down
;			  to 256x256
;	27-Oct-95 (MDM) - Modified the format of the AVG and DEV string format.
;			  Also display the average in the IDL window
;	 7-Nov-95 (MDM) - Modified so it doesn't crash if having a problem
;	 9-Nov-95 (MDM) - Removed setting of !order - display from bottom up
;	11-Dec-95 (MDM) - Corrected an error which resulted in WIN_IDX variable
;			  not being defined.
;	10-Jan-96 (MDM) - Added capability to congrid 1040x1033 images down to 
;			  256x256 for display purposes
;	17-Jan-96 (MDM) - Protected against stdev of a single value
;			- Added "Number of data pixels received does not match 
;			  the NXxNY value." statement
;	22-Jan-96 (MDM) - Modified to have /QCENTER option to display the center
;			  of the sun location
;	28-Mar-96 (MDM) - Modified to display the images which are not 1024 but are
;			  larger than 256 properly.
;	   Jul-96 (MDM) - Modified to work with EGSE 5.1
;	24-Jul-96 (MDM) - Replaced REBIN with CONGRID
;	16-Oct-96 (MDM) - Put in protection to never try to display a 1-D array
;	 5-May-97 (MDM) - Removed "retain=retain"
;-
;
common mdi_display3_blk, u
if (n_elements(u) ne 0) then begin  ; close up from last time through
    close, u
    free_lun, u
end
task_pn = string(format='((A),"/mdi_sci")',getenv("MDI_TASK_DIR"))
cmd = [task_pn, '-s 2','-x','-p']
if (getenv('EGSE_VER') ge '3.1') then cmd = [cmd, ' -a']		;MDM added 21-Sep-94
if (getenv('EGSE_VER') ge '5.1') then cmd = [task_pn, '-m','200','-a','-p', 'sci160k']
print, cmd
spawn, cmd, unit=u, /noshell
;
ccd_hdr = intarr(549)	; Buffer for CCD header block read
b = intarr(549)		; Buffer for data block read
avail = { block_addr : 0L, n_words : 0L }
string1='RT  MDI  160K  Image'
xwp = [16,824,16,824]
ywp = [704,704,16,16]
get_dpc_info, dpc_struct, /struct	; fill dpc_struct with dpc info
loadct,3
loops=0
;;!order = 1	; display from top down - removed 9-Nov-95
print, '**************************** !ORDER is now not set ****************************
print, 'The amplifier is in the lower left corner (CCD reads out DOWN and to the LEFT)
print, '********************************************************************************
tbeep, 3
ip_sync = 'DBE128BD'XL
first_img = 1
qdisp_con = keyword_set(qdisp_con)	;qdisp_con = 1			;display continously
nlin_disp = 64			;display 64 lines at a time
qsimple = 1			;do a simple min/max calculation
qdebug = keyword_set(qdebug)
retain = 2

;---- Set up the windows
if (not keyword_set(restart)) then begin
    for i=0,3 do begin
	window,i,title=string1,xsize=420,ysize=256,xpos=xwp(i),ypos=ywp(i)
	wshow,i,0
    endfor
;    window,5,title=string1,xsize=1188,ysize=1024,retain=2,xpos=46
    window,5,title=string1,xsize=420,ysize=256,xpos=46
    wshow,5,0
;    window,6,title="Temperatures",xsize=350,ysize=110,retain=2,ypos=(ywp(0)+ywp(3)+256)/2-55,xpos=xwp(0)
    window,6,title="Temperatures",xsize=350,ysize=110,ypos=783,xpos=456
    wshow,6,0
    window,7
    wshow,7,0
end
prevdp=0
newdp=1

ba = 999
;-------------------- The continuous main loop
while ( 1 eq 1) do begin
string14 = ''
string99 = ''
done = 0
block_ct = 0L
word_ct = 0L
block_addr = 0L
stop_addr = 0L
idx = 0L
temp = 0
dsos_mode = 0
block_size = 549L
data_product_code = 0L
n_full_blocks = 0L
image_words = 0L
part_block_words = 0L
img_size = 0
ip_sync_test = 0L
ip_exec_ct = 0
ip_src_page = 0L
ip_cksum = 0L
cam_temp = lonarr(10)
temp = fltarr(10)
iw = bytarr(4)

;;ba = 999		;MDM moved BA setting to outside the infinite while loop
skip = 0
while (ba ne 0) do begin
  if ((skip gt 0) and (skip lt 2)) then if (qdebug) then print,"Skipping blocks"
  readu,u,avail
  ba = avail.block_addr
  if (qdebug) then print, 'Waiting Loop.  BA = ', ba
  if (ba eq -1) then begin		;21-Sep-94 (MDM) - Change incorporated from RC.PRO
    writeu,u,avail.block_addr   ; acknowledge missed block
  endif
  if (ba gt 0) then begin
    skip = skip + 1
    writeu,u,avail.block_addr
    if (avail.n_words eq 0) then stop, 'NWORDS=0 problem in loop waiting for BA=0.  Stopping...'
    skbuf = intarr(avail.n_words)
    readu,u,skbuf
  endif
endwhile
if (skip gt 0)  then if (qdebug) then print,skip,format='("Skipped ",i6," blocks")'
;print,"*********************************************************************"
;print,"Assembling an image"
if (qdebug) then print,avail.block_addr,format ='("Available Block addr read is ",z10)'
;if (qdebug) then print,"Available n_words read is ",avail.n_words

if (keyword_set(qdp_interrupted)) then begin
    ccd_hdr = b
     if (qdebug) then print, 'Copying header from last read which interrupted
end else begin
    if (avail.n_words ne 549) then print, 'READING HEADER PROBLEM--OUTTA SYNC... AVAIL.N_WORDS <> 549
    writeu,u,avail.block_addr		;Tell 'em that we want the header block
    if (qdebug) then print,"Reading Header..."
    readu,u,ccd_hdr
end

ip_sync_test = long(ccd_hdr,502)
if (qdebug) then print,"ip_sync_test ",ip_sync_test
if ip_sync ne ip_sync_test then dsos_mode = 1
if (qdebug) then print,"dsos_mode ",dsos_mode
if dsos_mode eq 1 then begin
   ;  idx = 0
   ;  last_block = 118L
end
iw(0) = byte(ccd_hdr,6)
iw(1) = byte(ccd_hdr,7)
iw(2) = byte(ccd_hdr,4)
iw(3) = byte(ccd_hdr,5)
image_words = long(iw,0) - 549L
;if (qdebug) then print,"image_words: ",image_words
ip_exec_ct = fix(ccd_hdr,510)
ip_src_page = fix(ccd_hdr,512)
ip_cksum = fix(ccd_hdr,554)	; byte addr 554
;if (qdebug) then print,"ip_exec_ct: ",ip_exec_ct
;if (qdebug) then print,"ip_src_page: ",ip_src_page
;if (qdebug) then print,"ip_cksum: ",ip_cksum
;if (qdebug) then print,format='("ip_exec_ct: ",Z6)',ip_exec_ct
;if (qdebug) then print,format='("ip_src_page: ",Z6)',ip_src_page
;if (qdebug) then print,format='("ip_cksum: ",Z8)',ip_cksum

for i = 0,9 do begin
    cam_temp(i) = fix(ccd_hdr,510+i*4)
endfor
c_temp = ((cam_temp - 108.0)/4.0) - 150.0
c_temp = c_temp - c_temp(1)

  wset, 6
  erase
  wshow, 6
  t0_str = string (c_temp(0), "(' Ref = ', f7.2)")
  t1_str = string (c_temp(1), "('  T0 = ', f7.2)")
  t2_str = string (c_temp(2), "(' ADC = ', f7.2)")
  t3_str = string (c_temp(3), "('SCBd = ', f7.2)")
  t4_str = string (c_temp(4), "('VReg = ', f7.2)")
  t5_str = string (c_temp(5), "('Drvr = ', f7.2)")
  t6_str = string (c_temp(6), "('PROM = ', f7.2)")
  t7_str = string (c_temp(7), "('CCDA = ', f7.2)")
  t8_str = string (c_temp(8), "('CCDB = ', f7.2)")
  t9_str = string (c_temp(9), "('Case = ', f7.2)")
  !fancy = 0
  xyouts,   0, 90, t0_str, /device
  xyouts, 180, 90, t1_str, /device
  xyouts,   0, 70, t2_str, /device
  xyouts, 180, 70, t3_str, /device
  xyouts,   0, 50, t4_str, /device
  xyouts, 180, 50, t5_str, /device
  xyouts,   0, 30, t6_str, /device
  xyouts, 180, 30, t9_str, /device
  xyouts,   0, 10, t7_str, /device
  xyouts, 180, 10, t8_str, /device
  !fancy = 1

data_product_code = long(ccd_hdr,506)
if (qdebug) then print,data_product_code,format='("RAW DPC = ",z8)'
dpc_idx = where(dpc_struct.dpc eq data_product_code)
DataErr=0
if( dpc_idx(0) eq -1 ) then begin
   dpc_idx = where(dpc_struct.dpc eq '10000000'XL)	;the unknown code
   print, '**** UNKOWN Data Product Code - Allowing a 1040x1040 buffer size ****
   DataErr=1
   win_idx = 7		;MDM 14-Sep-95
   ;;image_words = tmp_dpc_struct.npix		;MDM 14-Sep-95, MDM removed 9-Oct-95
end
tmp_dpc_struct = dpc_struct(dpc_idx)
print,data_product_code,tmp_dpc_struct.mnem,format='($, "DPC = ",z8,"   ",A)'
string0 = tmp_dpc_struct.mnem		;MDM 21-Sep-94 (case statement
image_x = tmp_dpc_struct.nx
image_y = tmp_dpc_struct.ny
ItsATable = (tmp_dpc_struct.sum eq 0)
imin    = tmp_dpc_struct.imin
imax    = tmp_dpc_struct.imax
;;qcrop   = (data_product_code eq 'cfffff25'x) or (data_product_code eq 'cfffff26'x) $
;;			or (data_product_code eq 'cfffff28'x)	;MDM 14-Sep-95
qcrop = (image_y eq 1)						;MDM 13-Oct-95
if (qdebug) then print, 'QCROP = ', qcrop
image_words = image_words < tmp_dpc_struct.npix > 1	;MDM added 9-Oct-95
delvarx, a						;MDM added 9-Oct-95
a = intarr(image_words)
qdp_interrupted = 0

if (data_product_code eq prevdp) then newdp = 0 else newdp = 1
prevdp = data_product_code

;;if (DataErr eq 0) then begin
  last_ba = ((image_words / 549) + 1) * 549
  llin_disp = 0		;last line displayed
  repeat begin
        readu,u,avail
	ba = avail.block_addr
        if (ba eq 0L) then begin
          if (qdebug) then print, 'AVAIL.BLOCK_ADDR = 0'
	  print, 'A new data product interruted this downlink'
	  print, 'Wanted ', image_words, ' pixels, but only got', block_addr
          writeu,u,avail.block_addr       ; Tell 'em that we want the block
          b=intarr(avail.n_words) ;
          readu,u,b               ; Read into the block buffer
          done = 1
          ;;goto, image_done
	  qdp_interrupted = 1
          goto, image_done00
        endif
        if (ba eq -1L) then begin
          print, 'MISSED DATA'
          writeu,u,avail.block_addr   ; Tell 'em that we know we're out of sync
          goto, image_done
        endif
	;
	if (avail.n_words eq 0) then begin	;MDM 15-Sep-95
	    print, 'MDI_DISPLAY: Handshaking with MDI_SCI is all messed up.  N_WORDS = 0'
;;stop
            writeu,u,-1L   ; Tell 'em that we know we're out of sync
	    wait, 1
;;	    free_lun, u		;close the unit
;;	    spawn, cmd, unit=u, /noshell	;reopen the connection
            goto, image_done
	    ;;return
	end
        writeu,u,avail.block_addr       ; Tell 'em that we want the block
        b=intarr(avail.n_words) ;
        readu,u,b               ; Read into the block buffer
        ;;if block_addr+avail.n_words lt last_ba then a(block_addr) = b $
        if block_addr+avail.n_words lt image_words then begin
	  a(block_addr) = b
        end else begin
          done = 1
          stop_addr = image_words - block_addr - 1
;         if (qdebug) then print,stop_addr,image_words,block_addr
          a(block_addr) = b(0:stop_addr)
        endelse

        block_addr = block_addr + avail.n_words
	if (block_addr ge image_words) then done = 1		;MDM 14-Sep-95
        word_ct = word_ct + avail.n_words
        block_ct = block_ct + 1
	if (qdisp_con) then begin
	    clin = (block_addr / image_x) < image_y
	    if ((clin-llin_disp gt nlin_disp) or (done)) then begin
		nlin = clin-llin_disp
		ii0 = llin_disp*image_x
		ii1 = ii0 + (nlin)*image_x -1
		bimg = a(ii0:ii1)
		bimg = reform(bimg, image_x, nlin, /overwrite)
		llin_disp = llin_disp + nlin
		;tv, bytscl(bimg,max=imax,min=imin),164,llin_disp
		tv, bytscl(bimg,max=imax,min=imin),164,!d.y_size-llin_disp
	    end
	end

  endrep until done eq 1
  if (qdebug) then print, 'Finished getting an image from MDI_SCI'
  
  if dsos_mode eq 1 then begin
    for block_addr=0L,118L do begin
      a(block_addr) = b(block_addr)
    endfor
  endif

;--------------------------- start image display portion of the code
image_done00:

imgcongrid = 0
imgscl = 1.00
if (dataerr eq 1) then goto, image_done					;MDM 15-Sep-95
if (data_product_code eq 'cfffff98'x) then goto, image_done		;MDM 15-Sep-95
if (ItsATable eq 0) then begin	;not a table	(MDM moved from up above 15-Sep-95
    image_words = tmp_dpc_struct.npix	;not used for table - defined above by CCD header
    if (qcrop) then begin	;MDM 14-Sep-95
	image_x = 256
	image_y = 256
    end
    if (image_x eq 1024) then begin
	imgscl = 4.00
    end 
    if (image_x eq 1040) then imgcongrid = 1
    rpos = 0.35
    ;win_idx = loops mod 5
    win_idx = loops mod 4			;MDM 15-Sep-95
    loops = loops + 1			;sub counter?
end else begin
    win_idx = 7
end

  wset,win_idx
  wshow,win_idx
  ;if (not qdisp_con) then erase

 if (ItsATable) and (n_elements(a) lt 70000) then begin		;MDM added 70000 check 14-Sep-95
   ;wset,7
   ;wshow,7
   erase   
   plot,a
   goto,image_done
 end

  erase
  !fancy = 0			;MDM 14-Sep-95
  amin = min(a)
  amax = max(a)
  sdev = 0
  mean = 0
  if (n_elements(a) gt 2) then sdev=stdev(a, mean)
  if (qcrop) then begin
    ;;if (n_elements(pm) eq 0) then pm = rfits('/mdisw/dbase/ops/lists/pixmap256_crop.fits')
    ;;img = intarr(256, 256)
    ;;img( pm(*,1) ) = a( pm(*,0) )
    img = mk_dpc_image(256, a, data_product_code)
    if (n_elements(img) le 1) then goto,image_done
    if (n_elements(img(0,*)) eq 1) then goto,image_done		;MDM added 16-Oct-96
  end else begin
    if (n_elements(a) ne image_x*image_y) then begin
	print, 'Number of data pixels received does not match the NXxNY value.
	goto, image_done
    end
    ;;img = reform(a, image_x, image_y, /overwrite)	;MDM changed because of possible memory confusion with /OVERWRITE option
							;with different variable names
    img = temporary(a)				;rename the variable
    img = reform(img, image_x, image_y,/overwrite)
    ;;if (imgscl ne 1) then img = rebin(img, image_x/imgscl, image_y/imgscl)
    if (imgscl ne 1) then img = congrid(img, image_x/imgscl, image_y/imgscl)
    if (imgcongrid) then img = congrid(img, 256, 256)
    ;
    ;---- MDM added the following 28-Mar-96
    nnnx = n_elements(img(*,0))
    nnny = n_elements(img(0,*))
    if ((nnnx gt 256) or (nnny gt 256)) then begin
	scale = (256./nnnx) < (256./nnny)
	img = congrid(img, nnnx*scale, nnny*scale)
    end
  end
  if (not keyword_set(nodiff)) then begin
    if (first_img eq 1) then previmg = img
    if (newdp eq 0) then sdev2str = string(stdev(previmg-img),'(f6.2)')
  end else begin
    sdev2str = 'Not Calc''
  end
  first_img = 0
  if (keyword_set(qsimple)) then begin
    imin = amin
    imax = amax
  end else begin
    good = where ((img gt mean-3*sdev) and (img lt mean+3*sdev))
    imin = min(img(good))
    imax = max(img(good))
  end
;  if (min(img) gt (mean-3*sdev)) then imin = min(img) else imin = mean-3*sdev
;  if (max(img) lt (mean+3*sdev)) then imax = max(img) else imax = mean+3*sdev
  if (not qdisp_con) then tv,bytscl(img,max=imax,min=imin),164,0
  ;
  string2=string(ip_exec_ct,'(Z6)')
  string3=strmid(string2,strlen(string2)-4,4)
  
  string4=string(ip_src_page,'(Z6)')
  string5=strmid(string4,strlen(string4)-4,4)
  
  string6=string(ip_cksum,'(Z8)')
  string7=strmid(string6,strlen(string6)-4,4)
  
  string11='IMAGE TYPE:  '+string0
  string8= 'EXEC COUNT: '+string3
  string9= 'SRC PAGE  : '+string5
  string10='IP_CKSUM  : '+string7
  fancy=1
  string12=string(amin,'(i6)')
  string13=string(amax,'(i6)')
  string14=string(mean,'(f7.0)')
  string15=string(sdev,'(f6.0)')
  pos0 = .90
  ;;delpos = .10/imgscl
  delpos = .07
  pos = pos0
  xyouts,rpos,pos,string0,alignment=1.0,/normal,/noclip
  pos=pos-delpos
  ;xyouts,0.0,pos,"Count: ",/normal,/noclip
  ;xyouts,rpos,pos,string3,alignment=1.0,/normal,/noclip
  ;pos=pos-delpos
  ;xyouts,0.0,pos,"Page: ",/normal,/noclip
  ;xyouts,rpos,pos,string5,alignment=1.0,/normal,/noclip
  ;pos=pos-delpos
  xyouts,0.0,pos,"Loop: " + string(loops, format='(i6)'),/normal,/noclip
  pos=pos-delpos
  xyouts,0.0,pos,"DPC: " + string(data_product_code, format='(Z8.8)'),/normal,/noclip
  pos=pos-delpos
  string99 = string( ccd_hdr_info(ccd_hdr, 'FRAMEN'), format='(i4)')
  xyouts,0.0,pos,"FrameN: " + string99,/normal,/noclip
  pos=pos-delpos
  xyouts,0.0,pos,"RefTime: " + gt_time(ccd_hdr_info(ccd_hdr, 'reftime_str'), /str),/normal,/noclip
  pos=pos-delpos

  xyouts,0.0,pos,"Min: ",/normal,/noclip
  xyouts,rpos,pos,string12,alignment=1.0,/normal,/noclip
  pos=pos-delpos
  xyouts,.0,pos,"Max: ",/normal,/noclip
  xyouts,rpos,pos,string13,alignment=1.0,/normal,/noclip
  pos=pos-delpos
  xyouts,.0,pos,"Mean: ",/normal,/noclip
  xyouts,rpos,pos,string14,alignment=1.0,/normal,/noclip
  pos=pos-delpos
  xyouts,.0,pos,"SDev-I: ",/normal,/noclip
  xyouts,rpos,pos,string15,alignment=1.0,/normal,/noclip
  pos = pos-delpos
  if (newdp eq 0) then begin
    xyouts,.0,pos,"SDev-D: ",/normal,/noclip
    xyouts,rpos,pos,sdev2str,alignment=1.0,/normal,/noclip
    pos=pos-delpos
  endif
  if (keyword_set(qcenter)) then begin
    cen_xyr = pointing(img, thresh=thresh) * 4
    xyouts, .0, pos, /normal, /noclip, string('OCEN-X: ', cen_xyr(0), format="(a,f6.1)")	& pos = pos-delpos
    xyouts, .0, pos, /normal, /noclip, string('OCEN-Y: ', cen_xyr(1), format="(a,f6.1)")	& pos = pos-delpos
    xyouts, .0, pos, /normal, /noclip, string('OCEN-R: ', cen_xyr(2), format="(a,f6.1)")	& pos = pos-delpos
    print, string('  OCENTER:', cen_xyr, format="(a,3f7.1,$)")
  end
  if (qdebug) then print, "using extrema ",imin,imax
  dpc_struct(dpc_idx).imin = imin	;update the min value
  dpc_struct(dpc_idx).imax = imax
;;  endif  		;if (dataerr eq 0)
image_done:
  print, "                  image Done   " + string14 + string99
end	;---- End of the continous while loop

return
end

