pro WriteTags, Unit, Tags

	tagnames = TAG_NAMES(Tags)
	WRITEU, Unit, N_ELEMENTS(tagnames)
	for i = 0, N_ELEMENTS(tagnames)-1 do begin
		len = STRLEN(tagnames[i])
		WRITEU, Unit, len
		WRITEU, Unit, tagnames[i]
		type = SIZE(Tags.(i), /TYPE)
		WRITEU, Unit, type
		if type eq 7 then WRITEU, Unit, STRLEN(Tags.(i)) else WRITEU, Unit, N_ELEMENTS(Tags.(i))
		WRITEU, Unit, Tags.(i)
	endfor

end


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


pro ReadFileInfo_P3B, FileName, PIXEL_TYPE = pixtype, IMAGE_DIMENSIONS = dims, IMAGE_NUMBER = nframes

	OPENR, Unit, Filename, /GET_LUN
	ftags = ReadTags(Unit, NTAGS = numtags, MAXTAGS = 3)
	CLOSE, Unit
	FREE_LUN, Unit
	nframes = 1L
	dims = [ftags.DimX, ftags.DimY]
	pixtype = ftags.PixType

end


function Read_P3B, Filename, TAGS = tags, NTAGS = numtags

	OPENR, Unit, Filename, /GET_LUN
	ftags = ReadTags(Unit, NTAGS = numtags)
	CLOSE, Unit
	FREE_LUN, Unit
	if ARG_PRESENT(tags) then begin
		tagnames = TAG_NAMES(ftags)
		first = 1B
		tags = 0
		for i = 0, numtags-1 do begin
			if tagnames[i] eq 'DIMX' then continue
			if tagnames[i] eq 'DIMY' then continue
			if tagnames[i] eq 'DATA' then continue
			if tagnames[i] eq 'PIXTYPE' then continue
			tags = first ? CREATE_STRUCT(tagnames[i],ftags.(i)) : CREATE_STRUCT(tags, tagnames[i],ftags.(i))
			first = 0B
		endfor
		numtags = SIZE(tags, /TYPE) eq 8? N_TAGS(tags) : 0
	endif
	return, REFORM(ftags.Data, ftags.DimX, ftags.DimY, /OVERWRITE)

end


pro Write_P3B, Filename, Data, TAGS = tags

	struct = SIZE(Data, /STRUCTURE)
	dims = struct.Dimensions
	pixtype = struct.Type
	if N_ELEMENTS(tags) gt 0 then begin
		ftags = CREATE_STRUCT('DimX', dims[0], 'DimY',  dims[1], 'PixType', pixtype, 'Data', data, tags)
	endif else begin
		ftags = CREATE_STRUCT('DimX', dims[0], 'DimY',  dims[1], 'PixType', pixtype, 'Data', data)
	endelse
	OPENW, Unit, Filename, /GET_LUN
	WriteTags, Unit, ftags
	CLOSE, Unit
	FREE_LUN, Unit

end


