;+
; NAME:
;     TRUNCATE
; PURPOSE:
;     Routine to convert an archive file with zero-filled records
;     at the end into a generally smaller (truncated) archive file.
; CATEGORY:
;     OVRO APC DATA-ANALYSIS
; CALLING SEQUENCE:
;     truncate[,infile=infile][,outfile=outfile][,/delete][,/auto][,safe=safe]
; INPUTS:
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     infile   the name of the file to be truncated.  If omitted,
;                the user is prompted for an input file.
;     outfile  the name of the truncated file.  If omitted, the
;                user is prompted for an output file name.
;     delete   a flag that, if set, makes truncate attempt to
;                delete the input file after the truncation is
;                completed.  Note that the /AUTO keyword implies
;                the /DELETE keyword.
;     auto     a flag that, if set, causes the input file to
;                be read and automatically sets the output
;                name to Ddddhhmm.ARC where ddd is the day of
;                year, hhmm is the time of the first record in
;                the file.  Also, if /AUTO is used and no input
;                file is given, the file DAILY.ARC is assumed
;                if it exists.
; ROUTINES CALLED:
;     openarc getlrecn tl_decode
; OUTPUTS:
;     safe     a variable that is normally 0, but if set to 1 will
;                indicate that the calling program is to wait until
;                infile is deleted manually.  Used by WATCHER to avoid
;                annoying loop.
; COMMENTS:
; SIDE EFFECTS:
;     A file is created, and optionally another file is deleted
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 12-Jan-1998 by Dale E. Gary
;     22-Jun-1998  DG
;       Fix off-by-one error that wrote one blank record at the end
;       of truncated file.
;     27-Jun-1999  DG
;       Add lines to run quicklook and oview2web
;     24-Aug-1999  DG
;       Add NPLOT output to TRUNCATE so that OVIEW2WEB can be conditionally
;       run, since it doesn't work if there are no solar scans, so should
;       not be run.
;     03-Mar-2002  DG
;       Changed to handle new .PNG files--no need to call QUICKLOOK anymore.
;     18-Jul-2003 DG
;       Added SAFE keyword, to inform WATCHER to wait until DAILY.ARC is deleted.
;       Also added new language to popup window.
;-
pro truncate,infile=infile,outfile=outfile,delete=delete,auto=auto,safe=safe

   safe = 0
   ; Check whether an infile was given, and if not request one
   IF (NOT keyword_set(infile)) THEN BEGIN
      IF (keyword_set(auto)) THEN BEGIN
         infile = !DEFAULTS.DATADIR+'DAILY.ARC'
      ENDIF ELSE BEGIN
         infile = pickfile(path=!DEFAULTS.DATADIR,filter='*.arc',/READ)
         IF (infile EQ '') THEN return  ; User cancelled
      ENDELSE
   ENDIF

   ; Open the input file
   inlun = openarc(infile,a,nrec)
   IF (inlun EQ 0) THEN return      ; Could not open file

   ; Find the last record with good data
   lrec = getlrecn(a,nrec)

   ; Check whether an outfile was given, and if not request one
   IF (NOT keyword_set(outfile)) THEN BEGIN

      ; Suggest an output file name given by the date and time
      ; in the first record of the file
      tls = tl_decode(a(0))
      yrltr = string(byte((strmid(tls.yrday,0,4)-1929)))
      suggstn = yrltr+strmid(tls.yrday,5,3)+strmid(tls.timstr,1,2)+$
                                          strmid(tls.timstr,4,2)+'.ARC'

      ; If AUTO keyword is set, use the suggestion, otherwise ask
      ; the user to choose.
      IF (keyword_set(auto)) THEN BEGIN
         outfile = !DEFAULTS.DATADIR+suggstn
      ENDIF ELSE BEGIN
         outfile = pickfile(file=suggstn,path=!DEFAULTS.DATADIR,filter='*.arc',/WRITE)
         IF (outfile EQ '') THEN BEGIN
            free_lun, inlun
            return                   ; User cancelled
         ENDIF
      ENDELSE
   ENDIF

   ; Verify that the output file does not already exist.
   f = findfile(outfile,count=n)
   if (n ne 0) then begin
      ans = widget_message(['The file '+outfile+' already exists',' ',$
            'Please specify another filename'],/info)
      outfile = pickfile(file=outfile,path=!DEFAULTS.DATADIR,filter='*.arc',/WRITE)
      IF (outfile EQ '') THEN BEGIN
         free_lun, inlun
         goto,good_write                   ; User cancelled
      ENDIF
   endif
   ; Open the output file
   CATCH,err_stat
   IF (err_stat EQ 0) THEN BEGIN
      openw,/get_lun,outlun,outfile
      CATCH,/CANCEL
   ENDIF ELSE BEGIN
      ans = widget_message(!ERR_STRING,/ERROR)
      CATCH,/CANCEL
      free_lun, inlun             ; An error occurred in opening the file
      return
   ENDELSE

   ; Write the data from input to output file
   ON_IOERROR,bail
   FOR i = 0, lrec-1 DO BEGIN
      WRITEU,outlun,a(i)
   ENDFOR
   goto,good_write
bail:
   ; An error occurred while writing the file
   ans = widget_message(!ERR_STRING,/ERROR)
   free_lun,inlun
   free_lun,outlun
   return

good_write:
   free_lun,inlun
   if (n_elements(outlun) ne 0) then free_lun,outlun

   ; If the DELETE keyword was specified, or the auto keyword is
   ; specified, try to delete the input file
   IF (keyword_set(delete) OR keyword_set(auto)) THEN BEGIN
      openr,lun,/get_lun,infile,/delete
      close,lun
      free_lun,lun
      f = findfile(infile,count=n)
      if (n ne 0) then begin
         ans = dialog_message(['TRUNCATE: The new file was successfully written.',$
                            'However, TRUNCATE could not delete file '+infile,$
                            'Perhaps it is open by another process.',$
                            'End that process and delete the file manually',$
                            'It is safe to delete '+infile],/error)
         safe = 1
      endif
   ENDIF

   ; Create an overview plot and a web page entry.
   if (keyword_set(auto)) then begin
      ; Delete all .PNG files except for the _ALL.PNG file
      stem = filename2date(outfile,/nodelim)
      files = findfile(!defaults.webdir+stem+'*.png',count=n)
      if (n ne 0) then begin
         ; There were some .PNG files, so find the ones without _ALL in the name
         del = where(strpos(strupcase(files),'_ALL') eq -1,ndel)
         if (ndel ne 0) then begin
            ; There were some, so delete them all
            files = files[del]
            for i = 0, ndel-1 do begin
               openw,lun,/get_lun,files[i],/delete
               free_lun,lun
            endfor
         endif
      endif
      if (n ne 0) then oview2web,outfile
   endif

return
end