;+
; NAME:
;     FLARE_SORT
; PURPOSE:
;     Routine to read the flare database and return the sorted list
;     removing any multiple entries.
; CATEGORY:
;     OVRO APC DATA-ANALYSIS
; CALLING SEQUENCE:
;     lines = flare_sort([database=database][,/write])
; INPUTS:
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     database   optional filename to read.  If omitted, the
;                  standard database file, !defaults.dbdir+'flare.db'
;                  is used.
;     write      a switch that, if set, will write out the newly
;                  ordered lines to the same file (overwriting the
;                  existing file).
; ROUTINES CALLED:
; OUTPUTS:
;     lines      the sorted, unique list of lines from the file
; COMMENTS:
;     Note that multiple lines for the same flare may still exist,
;     if any part of the line differs (e.g. magnitude, etc.)
; SIDE EFFECTS:
;     Overwrites the specified database file with the results if
;     the WRITE keyword is set.
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 03-Mar-2002 by Dale E. Gary
;-
function flare_sort,database=database,write=write

   ; If DATABASE filename not given, default to main flare database
   if (not keyword_set(database)) then database = !defaults.dbdir+'flare.db'

   ; Open the database and determine the number of lines it has
   openr,lun,/get_lun,database
   hed = ''
   readf,lun,hed
   readf,lun,hed
   nbytperline = strlen(hed)+2  ; Assumes each line has CR-LF

   ; Determine number of bytes in the file, then close it
   nbytes = (fstat(lun)).size
   free_lun,lun

   ; Calculate the number of lines in the file
   nlines = float(nbytes)/nbytperline - 1
   lines = strarr(nlines)

   ; Reopen the file and read the data
   openr,lun,/get_lun,database
   readf,lun,hed
   readf,lun,lines

   ; Sort the lines
   lines = lines[sort(lines)]

   ; Keep only unique lines
   lines = lines[uniq(lines)]

   free_lun,lun

   ; If the WRITE keyword is set, then write out the new lines,
   ; overwriting the existing file
   if (keyword_set(write)) then begin
      openw,lun,/get_lun,database
      printf,lun,[hed,lines],format='(a)'
      free_lun,lun
   endif

return,[hed,lines]
end
