;+
;
;  Name:
;       READ_MONTH_CAT
;  
;
; PURPOSE:
; 	This procedure writes the BATSE flare catalog into monthly files.
; CATEGORY:
;	 batse archive i/o
;
; CALLING SEQUENCE: 
;	read_month_cat
;
; CALLED BY:
;
;
; CALLS:
;	none
;
; INPUTS:
; 	none
;
; OPTIONAL INPUTS:
;	Month - a single date (anytim format), return the catalog
;		only for this month which includes this date.
;
; OUTPUTS:
;       none explicit, only through commons;
;
; OPTIONAL OUTPUTS:
;	Fldata_month - the catalog structure for the month is
;	the input Month is present.
;
; KEYWORD OUTPUTS:
;	ERROR - returns (0/1) if the file indicated by Month is/not present.
;
; COMMON BLOCKS:
;	flare_catalog
;
; SIDE EFFECTS:
;	none
;
; RESTRICTIONS:
;	none
;
; PROCEDURE:
;	This procedure finds the batse flare catalog monthly files,
;	opens them and reads them into the common catalog area.  This
; 	procedure was written to support the modularization of the
;	catalog to facilitate broadcast using SSW.  Written mainly
;	as a test of the technique.
;
; MODIFICATION HISTORY:
;	Version 1, richard.schwartz@gsfc.nasa.gov, 18-nov-1997
;-
pro read_month_cat, month, fldata_month, error=error

@flare_catalog

cat_home = getenv('BATSE_MONTH_CATALOG')
cd, cat_home,current=current
if keyword_set(month) then begin
;
;  Find  only 1 month's catalog.
;
	
	month = anytim( month, /ex, /date)
	month(4) = 1
	month = time2file( anytim(month,/ints), /date )
	files = findfile('batse_flare_' + month(0) + '.cat', count=nfile)
	endif else files = findfile('batse_flare_*.cat', count=count)
cd, current
break_file,files, disk, dir, fname, ext

fname = concat_dir( cat_home, fname + ext)
loghead = {head_index2, flares_this_month:0L, date_written:0.d0, spare_head: lonarr(61)}

@batse_log_struct

if keyword_set(month) then begin
;
;  Read in only 1 month's catalog.
;
	
	error = 1 - nfile
	if nfile then begin
		openr, lun,/get, fname(0)
		readu, lun, loghead
		ieee_to_host, loghead
		fldata_month = replicate( batlog, loghead.flares_this_month)
		readu, lun, fldata_month
		ieee_to_host, fldata_month
		free_lun, lun
		endif else fldata_month = batlog 
	endif else begin

	s=sort(fname)
	num_flares_temp = 0L

	for i=0,count-1 do begin
		openr, lun,/get, fname(i)
		readu, lun, loghead
		ieee_to_host, loghead
		num_flares_temp = num_flares_temp + loghead.flares_this_month
		free_lun, lun
		endfor

	fldata = replicate( batlog, num_flares_temp )
	num_flares = num_flares_temp 	;only replace the value in common after creating fldata!
	for i=0,count-1 do begin
		openr, lun,/get, fname(i)
		readu, lun, loghead
		ieee_to_host, loghead
		temp = replicate( batlog, loghead.flares_this_month)
		readu, lun, temp
		ieee_to_host, temp
		free_lun, lun
		fldata( temp.flare_num-1) = temp
		endfor
	endelse

end

