function AIA_BP_READ_ERR, filename, $
	warnings, $
	logdir = logdir, silent = silent

;+
;
; $Id: aia_bp_read_err.pro,v 1.1 2010/05/28 22:31:25 boerner Exp $
;
; Reads in an err.txt file and returns an IDL structure containing the
; parameters of the calibration error.
;
; INPUT:	
;	filename-	the name of the err.txt file to be read (including 
;				the path, if necessary, from the current directory; 
;				generally, no path should be used, and the function
;				should be run from the appropriate directory)
;
; RETURNS:
;	errstr-		a structure giving the error parameters
;
; OUTPUT:
;	warnings-	[OPTIONAL] a string array containing any descriptive
;				text on potential errors encountered during the generation
;				of the response structure
;
; KEYWORDS:
;	/silent-	if set, nothing is printed to the terminal
;
;	logdir=		if set, the warnings are written to a text file in the logdir
;
; $Log: aia_bp_read_err.pro,v $
; Revision 1.1  2010/05/28 22:31:25  boerner
; Initial version
;
;
;-

errors = ''
warnings = ''

result = RD_TFILE(filename, 3, /nocomm, /compress, delim = '-')
rsize = SIZE(result)


; Set up the calibration error structure and fill it with the defaults
errstr_template = {Name : 'Simple', Norm : 0.0, Noise : 0.0, NoiseSmooth : 0.0, $
	Wshift : 0.0}
ntags = N_ELEMENTS(errstr_template)
tagnames = TAG_NAMES(errstr_template)


; Identify the types of components which have some degree of error specified 
; in the error file
comps = result[0,*]
compsort = SORT(comps)
ucompsort = UNIQ(comps[compsort])
ucomps = comps[ucompsort]	;	a list of all components with errors
ncomps = N_ELEMENTS(ucomps)


; For each component, fill in an error structure with the values specified in the file
for i = 0, ncomps - 1 do begin
	thiscomp = ucomps[i]
	substr = errstr_template
	substr.name = thiscomp
	complines = WHERE(result[0,*] eq thiscomp, numlines)

	; For each component, go through and see whether each type of error is specified.
	; If not (or if it is specified redundantly), set it to 0 and print a warning
	substr = AIA_BP_FILE2TEMPLATE(errstr_template, result[*,complines], $
		warnings = warnings)

	if i eq 0 then errstr = substr else errstr = [errstr, substr]
endfor


; Check for errors and inconsistencies, and write out a warning log file
; if necessary
numwarn = N_ELEMENTS(warnings)
if numwarn gt 1 then begin
	warnings = warnings[1, numwarn-1]	;	drop the dummy first element
	if not KEYWORD_SET(silent) then PRINT, warnings
	if KEYWORD_SET(logdir) then begin
		sepfile = STRSPLIT(/extract, filename, '.')
		warnfile = AIA_BP_DATE_STRING(/time) + '_' + sepfile[0] + '_warn.txt'
		CD, logdir, current = old_dir
		OPENW, loglun, /get_lun, warnfile
		PRINTF, loglun, warnings
		CLOSE, loglun
		CD, old_dir
	 endif
endif 

RETURN, errstr

end

