;** use '971130', 'c2' (or 'c3')

FUNCTION MAKE_DAILY_IMAGE, date, tele, TIME=time, FITS=fits, GIF=gif, LZ=lz, SCREEN=screen, ARCHIVE=archive

;+
; NAME:
;	MAKE_DAILY_IMAGE
;
; PURPOSE:
;	This function generates the daily image for the SOHO summary images.
;
; CATEGORY:
;	LASCO_SYNOPTIC
;
; CALLING SEQUENCE:
;	Result - MAKE_DAILY_IMAGE (Date, Tele)
;
; INPUTS:
;	Date:	Date for which the image is desired, (YYMMDD)
;		If undefined, then uses the current date
;	Tele:	Telescope designator, string of 'c2','c3'
;
; KEYWORD PARAMETERS:
;	TIME:	If set use the image closest to the specified time (HHMM)
;		else uses the latest image
;	FITS:	If set create a FITS file as output
;	GIF:	If set create a GIF file as output
;	LZ:	IF set, use level 0 data else use quick look data
;	SCREEN:	If set, writes the resultant image to the current display
;		else writes to the Z buffer
;	ARCHIVE:	If set, write to the SOHO Summary file area
;
; OUTPUTS:
;	Result:	Returns the byte-scaled image if successful, else returns -1.
;
; RESTRICTION:
;	Only works for C2 and C3
;
; PROCEDURE:
;	If the input parameter, date, is defined, then that date is used
;	otherwise the current date is used.  Then reads in the img_hdr.txt 
;	file corresponding to the desired date.
;	Finds the image that is closest to the input time if set, else
;	finds the latest image.  The standard synoptic type of image is
;	selected (C2: orange/clear; C3: clear/clear).  The image shold
;	be large enough and not have too many missing blocks.
;	Then the image is scaled by the background model.
;
; EXAMPLE:
;	cimg = MAKE_DAILY_IMAGE('960810','c3')
;
; MODIFICATION HISTORY:
; 	Written by:	S.E. Paswaters, NRL, Dec 1997
;	1/31/01, nbr - Change bkg model settings for C2
;
;	%H% %W% LASCO IDL LIBRARY
;
;-

   curr_device = !D.NAME
   SET_PLOT, 'Z'
   DEVICE, SET_RESOLUTION=[1024,1024]

   cimg = -1

 IF (DATATYPE(date) EQ 'UND') THEN BEGIN	;** use current date
    GET_UTC, utc
    date = UTC2YYMMDD(utc)
 ENDIF

   tel = STRLOWCASE(tele)
   IF KEYWORD_SET(LZ) THEN img_dir = GETENV('LZ_IMG') ELSE img_dir = GETENV('QL_IMG')

   CASE (tel) OF 
      'c2' : BEGIN
                fw = 'Orange'
                pw = 'Clear'
                naxis1 = 1024
                naxis2 = 1024
                bmin = 0.8
                bmax = 1.7
                coords=[0,1023,0,1023]
                box=[261,760,696,795]
                box_ref=2000.	;** 2x2 summed
                model_all=0
                model_any_year=0
                LOADCT, 3
                r_occ = 2.2
                r_occ_out = 7.0
                fillcol=128
                max_datazer = 66000L
             END
      'c3' : BEGIN
                fw = 'Clear'
                pw = 'Clear'
                naxis1 = 1024
                naxis2 = 1024
                bmin = 0.9
                bmax = 1.15
                coords=[0,1023,0,1023]
                box=[261,760,750,799]
                box_ref=1600.	;** 2x2 summed
                model_all=0
                model_any_year=0	; ** set 2/26/99, NBR
                LOADCT, 1
                GAMMA_CT, 0.6
                r_occ = 4.3
                r_occ_out = 32.0
                fillcol=128
                max_datazer = 110000L
             END
      ELSE : BEGIN
                PRINT, '%%MAKE_DAILY_IMAGE: Unknown telescope: ', tel
                PRINT, '%%MAKE_DAILY_IMAGE: Currently only works for C2 & C3'
                RETURN, -1
             END
   ENDCASE

   utc = YYMMDD2UTC(date)

   dir = img_dir+'/level_05/'+date+'/'+tel+'/'
   stc = IMG_HDR_TXT2STRUCT(dir+'img_hdr.txt')

   IF (DATATYPE(stc) NE 'STC') THEN RETURN, -1

   good = WHERE( (stc.fw EQ fw) AND (stc.pw EQ pw) AND $
                ((stc.naxis1 GE naxis1) AND (stc.naxis2 GE naxis2)) AND $
                 (stc.lp NE 'Sum/Diff') )

   IF (N_ELEMENTS(good) EQ 1) THEN BEGIN
      PRINT, '%%MAKE_DAILY_IMAGE: No images found for: ', dir
      RETURN, -1
   ENDIF
   stc = stc(good)

   ;** if user passes a time then take image closest to that time
   ;** otherwise use latest image without too many missing blocks
   IF KEYWORD_SET(TIME) THEN BEGIN
      ;** sort by date
      d = SORT(stc.time)
      stc = stc(d)
      times = UTC2TAI(STR2UTC(stc.time))
      atime = UTC2TAI(STR2UTC(time))
      ind = FIND_CLOSEST(atime, times)
      filename = dir+stc(ind(0)).filename
      fits_hdr = HEADFITS(filename)
   ENDIF ELSE BEGIN
      ;** reverse sort by date
      d = REVERSE(SORT(stc.time))
      stc = stc(d)
   
      list = stc.filename
      list = dir+list
      f=0
      datazer = max_datazer+1
      WHILE (datazer GT max_datazer) DO BEGIN	;** skip files with too many missing blocks
         IF (f GE N_ELEMENTS(list)) THEN RETURN, -1
         filename=list(f)
         ok = FILE_EXIST(filename)
         IF (ok EQ 1) THEN BEGIN
            fits_hdr = HEADFITS(filename)
            datazer = FXPAR(fits_hdr, 'DATAZER')
         ENDIF
         f=f+1
      ENDWHILE
   ENDELSE

   ok = FILE_EXIST(filename)
   IF (ok EQ 1) THEN BEGIN

      img = LASCO_READFITS(filename, hdr)
      imgm = GETBKGIMG(hdr, mhdr, ALL=model_all, ANY_YEAR=model_any_year)
      bias = OFFSET_BIAS(hdr, /SUM)
      img = FLOAT(img) - bias			;subtract detector bias from image
      cimg = img * (mhdr.exptime/hdr.exptime)   ;normalize to exposure time of model image

      nonzero = WHERE(imgm NE 0)
      cimg(nonzero) = TEMPORARY(cimg(nonzero)) / imgm(nonzero)   ;take ratio of image to model

      ;test = CCOSMICS(BYTARR(10,10))
      ;IF (N_ELEMENTS(test) EQ 1) THEN BEGIN
      ;   POINT_FILTER,cimg,5,7,3,tmp,pts
      ;   cimg = tmp
      ;ENDIF ELSE BEGIN
      ;   cimg = CCOSMICS(cimg)
      ;ENDELSE

      TVLCT, r, g, b, /GET
      cimg = BYTSCL(cimg, bmin, bmax)

      sunc = GET_SUN_CENTER(hdr, /NOCHECK)
      arcs = GET_SEC_PIXEL(hdr)
      asolr = GET_SOLAR_RADIUS(hdr)
      r_sun = asolr/arcs

      ;** draw mask
      tmp_img = cimg & tmp_img(*) = 0 & TV,tmp_img
      TVCIRCLE, r_occ_out*r_sun,sunc.xcen,sunc.ycen, /FILL, COLOR=1
      tmp_img = TVRD()
      ind1 = WHERE(tmp_img NE 1)
      IF (ind1(0) NE -1) THEN cimg(ind1) = fillcol

      ;** add logo
      cimg = ADD_LASCO_LOGO(cimg)

      TV, cimg

      TVCIRCLE, r_occ*r_sun, sunc.xcen, sunc.ycen, /FILL, COLOR=fillcol

      ;** draw limb
      TVCIRCLE, r_sun, sunc.xcen, sunc.ycen, COLOR=255, THICK=2

      XYOUTS, 10, 35, '!3SOHO/LASCO-'+STRUPCASE(tel), /DEVICE, CHARSIZE=2.0
      XYOUTS, 10, 10, STRMID(hdr.date_obs + ' ' + hdr.time_obs, 0, 16), /DEVICE, CHARSIZE=2.0

      cimg = TVRD()

      name = 'slas_'+tel+'wlc_fd_'+STRMID(hdr.date_obs,0,4)+STRMID(hdr.date_obs,5,2)+$
             STRMID(hdr.date_obs,8,2)+'_'+STRMID(hdr.time_obs,0,2)+STRMID(hdr.time_obs,3,2)
      IF KEYWORD_SET(ARCHIVE) THEN BEGIN
         summary = GETENV('SUMMARY')
         name = summary+'/lasco/'+name
      ENDIF

;** add DATE_OBS to FITS hdr
s = FXPAR (fits_hdr,'DATE_OBS')
IF (s EQ '') THEN BEGIN
   s = FXPAR (fits_hdr,'DATE-OBS') + ' ' + FXPAR(fits_hdr,'TIME-OBS')
   utc = STR2UTC(s)
   dly = LONG ( 1000 * GET_TIME_DELAY ( utc ) )   ; # msec from SOHO to Earth
   IF (dly lt 0)    THEN dly = 5300               ; assume 1.6e6 km from earth
   utc.time = utc.time+dly
   IF (utc.time GT 86400000L)  THEN BEGIN
      utc.time = utc.time-86400000L
      utc.mjd  = utc.mjd+1
   ENDIF
   FXADDPAR,fits_hdr,'DATE_OBS',UTC2STR(utc),AFTER='TIME-OBS','DATE/TIME at earth'
ENDIF

      IF KEYWORD_SET(FITS) THEN WRITEFITS, name+'.fts', cimg, fits_hdr
      IF KEYWORD_SET(GIF) THEN WRITE_GIF, name+'.gif', cimg, r, g, b

      IF KEYWORD_SET(SCREEN) THEN BEGIN
         SET_PLOT, 'x'
         AWIN, cimg
         TVLCT, r, g, b
         TV, cimg
      ENDIF

   ENDIF

   SET_PLOT, curr_device
   RETURN, cimg

END
