;+
; PROJECT:
;	SXI-M Ground Data System
;
; NAME:
;	MAKE_BROWSE
;
; PURPOSE:
;   Generate byte images for browsing and real-time display.
;
; EXPLANATION:
;	TBS
;
; CALLING SEQUENCE:
;	MAKE_BROWSE,image,index,image_type,level,browse,stamp
;
; INPUTS:
;	image			=	input image (512x512)
;	index			=	input header (from FITS) as index structure
;   image_type		=	image type, e.g., flare, etc.
;	level			=	image level code, e.g., A=level-0, B=level-1
;
; OUTPUTS:
;	browse			=	browse image array with annotation (512x512 byte array)
;	stamp			=	stamp image array with no annotation (128x128 byte array)
;
; OPTIONAL INPUT KEYWORDS:
;	N/A
;
; EXTERNAL CALLS:
;	N/A
;
; CALLED BY:
;	SXIG12_PREP
;
; METHOD:
;	TBS
;
; HISTORY:
;   001.001  Written by Steven Hill at NOAA/SEC 30 Jan 2001
;   001.002  Modified by SMH 4/6/2001
;            Removed full path for level-1 circular mask file
;            Added color bar on left side of full sized images
;   001.003  Modified by SMH 7/10/2001
;            Added correct ph/pix/sec scaling for level-1 PNGs
;   001.004  Modified by SMH 7/26/2001
;            Accommodated message for missing TSYNC packet
;            impact on MCP gain computation
;   003.001  Modified by VJP 8/13/2001
;            changed mask read to byte array
;            changed mask test so that mask only applied for 'SUN' images
;   003.002  Modified by SMH 9/10/2001
;            Made display scales fixed at 0-1023 for level-0 and
;            0 to the maximum possible for level-1 images
;            Changed MCP and exposure time to settings instead of
;            measured actuals.
;   003.003  Modified by SMH 9/19/2001
;            Set maximum for level-1 files based on MCP gain setting
;            and an offset value to get around measurement noise on
;            MCP1K_V telemetry
;   003.004  Modified by SMH 9/20/2001
;            Added incremental scaling so that underexposed images
;            could be seen
;   003.005  Modified by SMH 9/21/2001
;            Scale level-1 images based on MCP_GAIN rather than MCP1K_V info
;            in BSCALE.  Noise in MCP1K_V measurement makes images flicker.
;            Need a long-term solution to this.
;   003.006  Modified by SMH 9/21/2001
;            Added logic to exclude WAVELNTH='RDSH' images from level-1 scaling.
;            Previously had been screening on IMAGE_TYPE='BG', but for new
;            ESTs that is sometimes 'TST' instead.
;   003.007  Modified by SMH 9/24/2001
;            Commented out incremental scaling from 003.004 and replaced with
;            fixed base 10 logarithmic scaling.
;   003.008  Modified by SMH 10/3/2001
;            Fixed date-time parsing error for month
;   003.009  Modified by SMH 10/29/2001
;            Moved dn-to-photons conversion to independent function
;   003.010  Modified by SMH 11/19/2001
;            Changed Level-1 scaling from ph/s to DN/s due to uncertainty
;            in MCP gain linearity
;   003.011  Modified by SMH 05/17/2002
;            Changed name to sxi_make_browse from make_browse
;            Changed call to sxim_dn2photons to sxig12_dn2photons
;   003.012  Modified by SMH 6/11/2002
;            Added notation to browse image to indicate images taken
;            with logarithmic amplifier
;            Removed MCP error message, removed msg as a passed parameter.
;            Error displays will now be based on index paramaters
;   003.013  Modified by SMH 6/12/2002
;            Changed date-time format in browse images to be more
;            consistent with SQL and CCSDS formats
;   003.014  Modified by SMH 4/22/2003
;            Changed MAXSCALE to SCALE_FACTOR which is based only on
;            DN/s rather than fudging a DN2PH of unity to retain future
;            options with physical units. For level-1 products, set
;            SCALE_FACTOR=4.0 to minimize monitor saturation when
;            instrument saturated pixels have been replaced.
;            Set IMGSCALE to unity.
;            Added character 'C' to PNG annotation when sat. pix.
;            are replaced to indicated 'composite' image
;-
pro sxi_make_browse,image,index,image_type,level,browse,stamp
;;;;;;;;;;;;;;;;;;
; Initialization ;
;;;;;;;;;;;;;;;;;;

chsize=1.4 ; Z-buffer device
sz=512
set_plot,'Z'
device,set_resolution=[sz+64,sz]

if n_elements(image) gt 1 then begin  ; Error handling for no image array
  if level eq 'B' and index.object eq 'SUN' then begin
    openr,1,'mask001.bin'
    tmp=assoc(1,bytarr(512,512))
    mask=tmp(0)
    close,1
    image=image*mask
  endif

;;;;;;;;;;;;;;;;;;;;;
;                   ;
; Determine scaling ;
; max and min and   ;
; write image to    ;
; Z-buffer          ;
;                   ;
;;;;;;;;;;;;;;;;;;;;;

  if level eq 'A' or index.WAVELNTH eq 'RDSH' then begin
    maxbright=alog10(1023.0) ;Units=Log10(DN)
    minbright=alog10(   1.0) ;Units=Log10(DN) -- use 1.0 because of log scale
  endif
  if level eq 'B' and index.WAVELNTH ne 'RDSH' then begin
    if fix(index.EXPTIME) eq 3 then begin
      scale_factor=4.0
    endif else begin
      scale_factor=1.0
    endelse
    maxbright=index.BZERO+scale_factor*1023.0/index.EXPTIME ;Units=Ph/sec
    minbright=index.BZERO+scale_factor*   1.0/index.EXPTIME ;Units=Ph/sec
    maxbright=alog10(maxbright)
    minbright=alog10(minbright)
    ;scale image ****Can't use bscale because it has too much noise from
    ;                MCP1K_V.  Need a longer term solution - SMH 9/21/2001

;    imgscale=sxig12_dn2photons(1000.,exponent=1.0,factor=1.0)
    imgscale=1.0
;
; Changed to DN/S for display because of uncertainty in MCP gain
;  SMH 11-19-2001
;
    image=index.bzero+float(image)*imgscale ;Units=Ph/sec
  endif
    image=alog10(image>(10^minbright))
; Adjust maximum brightness geometrically in steps
  ;logbase=2.0
  ;bright_ratio=max(image)/maxbright
  ;bright_ratio_log10=alog10(bright_ratio)
  ;bright_ratio_log=bright_ratio_log10/alog10(logbase)
  ;bright_scale=float(ceil(bright_ratio_log))
  ;maxbright=maxbright*logbase^bright_scale
;  tv,255.*((image>minbright)<maxbright)/(maxbright-minbright),63,0
  tv,255.*((image-minbright)<(maxbright-minbright))/(maxbright-minbright),63,0


;;;;;;;;;;;;;;;;;;;;;;
;                    ;
; Generate Color Bar ;
;                    ;
;;;;;;;;;;;;;;;;;;;;;;

  color_bar=findgen(350)*256./350.
  cbar=fltarr(64,512)
  for i=39,55 do cbar(i,70:419)=color_bar(0:349)
  tvscl,cbar,0,0

;;;;;;;;;;;;;;;;;;;;;;
;                    ;
; Generate and write ;
; scale for Level-0  ;
;                    ;
;;;;;;;;;;;;;;;;;;;;;;

  if level eq 'A' or index.WAVELNTH eq 'RDSH' then begin
    xyouts,31,470,'Scale',/device,charsize=chsize*0.8,alignment=0.5
    xyouts,31,450,'(DN)',/device,charsize=chsize*0.8,alignment=0.5
    scale_values=10^(minbright+float(findgen(11))*(maxbright-minbright)/10.)
    scale_strings=strmid(strtrim(scale_values,2),0,4)
    for i=0,10 do xyouts,36,70+i*25.6*350./255.,scale_strings(i),/device,charsize=chsize*0.8,alignment=1.0
  endif

;;;;;;;;;;;;;;;;;;;;;;
;                    ;
; Generate and write ;
; scale for Level-1  ;
;                    ;
;;;;;;;;;;;;;;;;;;;;;;

  if level eq 'B' and index.WAVELNTH ne 'RDSH' then begin ;**********
    scale_log10=floor(maxbright)-2
    xyouts,31,480,'Scale',/device,charsize=chsize*0.8,alignment=0.5
    xyouts,31,460,'(10!e'+strtrim(scale_log10,2)+'!n', $
      /device,charsize=chsize*0.8,alignment=0.5
;    xyouts,31,440,'ph/s)',/device,charsize=chsize*0.8,alignment=0.5
;  MCP Gain scale replaced by DN/sec SMH 11-19-2001
    xyouts,31,440,'DN/s)',/device,charsize=chsize*0.8,alignment=0.5

    if strmid(index.shrtdark,0,5) eq 'ERROR' then begin
      error_box=bytarr(64,64)
      tv,error_box+255
      xyouts,31,44,'ERROR',/device,charsize=chsize*0.8,alignment=0.5,color=0
      xyouts,31,24,'Dark',/device,charsize=chsize*0.8,alignment=0.5,color=0
      xyouts,31,4,'Frame',/device,charsize=chsize*0.8,alignment=0.5,color=0
    endif

    if strmid(index.longdark,0,5) eq 'WARNI' then begin
      error_box=bytarr(64,64)
      tv,error_box+255
      xyouts,31,44,'WARNG',/device,charsize=chsize*0.8,alignment=0.5,color=0
      xyouts,31,24,'Dark',/device,charsize=chsize*0.8,alignment=0.5,color=0
      xyouts,31,4,'Frame',/device,charsize=chsize*0.8,alignment=0.5,color=0
    endif

;SCALE VALUES ASSUMES MINIMUM VALUE IS ZERO
;    scale_values=(float(findgen(10))* maxbright/8.)/(10.0^float(scale_log10))
    scale_values=(10^(minbright+float(findgen(11))*(maxbright-minbright)/10.))/(10.0^float(scale_log10))

    scale_strings=strmid(strtrim(scale_values,2),0,4)
    for i=0,10 do xyouts,36,70+i*25.6*350./255.,scale_strings(i),/device,charsize=chsize*0.8,alignment=1.0
    ;stop
  endif

;;;;;;;;;;;;;;;;;;;;;;;;;;
;                        ;
; Set up strings for GIF ;
;                        ;
;;;;;;;;;;;;;;;;;;;;;;;;;;

  datestring=str_replace(index.DATE_OBS,'T',' ')
  datestring=str_replace(datestring,'-','/')
  datestring=strmid(datestring,0,19)+' UTC'

  if level eq 'A' then lvl='Raw'
  if level eq 'B' then begin
    lvl='Level-1'
    if index.sat_pix gt 1 then lvl='Level-1C'
  endif

  offset=63

  xyouts,offset+4,490,index.TELESCOP,/device,charsize=chsize
  xyouts,offset+120,490,index.INSTRUME,/device,charsize=chsize
  xyouts,offset+190,490,image_type,/device,charsize=chsize
  xyouts,offset+250,490,lvl,/device,charsize=chsize
  xyouts,offset+460,490,strtrim(index.EXP_INDX,2),/device,charsize=chsize
  xyouts,offset+460,472,index.LIN_LOG,/device,charsize=chsize

  xyouts,offset+4,4,datestring,/device,charsize=chsize
  xyouts,offset+280,4,index.WAVELNTH,/device,charsize=chsize
  xyouts,offset+380,4,strmid(strtrim(index.INT_TIME,2),0,5)+'s',/device,charsize=chsize
  xyouts,offset+460,4,strmid(strtrim(index.MCP_GAIN,2),0,3)+'V',/device,charsize=chsize

  xyouts,offset+4,472,'NOAA/SEC',/device,charsize=chsize*0.8
  xyouts,offset+4,456,'Boulder, CO',/device,charsize=chsize*0.8,alignment=0.0

  browse=tvrd()
  stamp=bytscl(rebin(image,128,128))
endif else begin
  browse=-1
  stamp=-1
endelse

end
