; Copyright (c) 2007 A. Scholl  All rights reserved
;+
;NAME:
;		READ_TAGS
;
;LAST CHANGED: ----------------------------------- 	12-Sep-07
;
; PURPOSE:
;	This function reads parameters from an embedded structure in the ALS PEEM3 data format
;
; CATEGORY:
;	utility
;
; CALLING SEQUENCE:
;	Result =  ReadTags, Unit, TAGS = Tags, NTAGS = numtags, MAXTAGS = maxtags
;
; INPUTS:
;	Unit	open file unit number
;	Tags	parameters with associated Tag names (IDL structure)
;	NTags	number of tags
;	MaxTags	maximum number of tags
;
; KEYWORDS: none
;
; OUTPUTS: adds tags to data file
;
; COMMON BLOCKS: none
;
;
; MODIFICATION HISTORY:
; (20-Jan-07 aph) extracted from filetype_p3b.pro (20-jan-07 version of A. Scholl)
; (12-sep-07 aph) update to version sent late Jan-07 (seemed the same)
;-

function ReadTags, Unit, TAGS = Tags, NTAGS = numtags, MAXTAGS = maxtags


    copy = 0B
    if N_ELEMENTS(Tags) gt 0 then if SIZE(Tags,/TYPE) eq 8 then copy = 1B
    if copy then begin
            RTags = Tags
            tagnames = STRUPCASE(TAG_NAMES(RTags))
    endif
    numtags = 0L
    len = 0L
    type = 0L
    READU, Unit, numtags
    if N_ELEMENTS(maxtags) gt 0 then numtags <= maxtags
    for i = 1, numtags do begin
            READU, Unit, len
            tag = STRING(MAKE_ARRAY(len, /BYTE, VALUE = 32B))
            READU, Unit, tag
            READU, Unit, type
            READU, Unit, len
            if len gt 0 then begin
                    if type eq 7 then begin
                            val = STRING(MAKE_ARRAY(len, /BYTE, VALUE = 32B))
                    endif else begin
                            val = FIX(0, TYPE = type)
                            if len gt 1 then val = REPLICATE(val,len)
                    endelse
                    READU, Unit, val
                    if copy then begin
                            tagindex = (WHERE(tagnames eq STRUPCASE(tag)))[0]
                            if (tagindex ge 0) and SIZE(RTags.(tagindex), /TYPE) eq type then RTags.(tagindex) = val
                    endif else begin
                            RTags = i eq 1 ? CREATE_STRUCT(tag, val) : CREATE_STRUCT(RTags, tag, val)
                    endelse
            endif
    endfor
    return, RTags

end