def Interchange.parse( hnd=$stdin, auto_validate=true )
ic = nil
buf = hnd.read
return ic if buf.empty?
ic, segment_list = Interchange.parse_buffer( buf )
if ic.is_iedi?
init_seg = Regexp.new('^UIB'); tag_init = 'UIB'
exit_seg = Regexp.new('^UIZ'); tag_exit = 'UIZ'
else
init_seg = Regexp.new('^UNB'); tag_init = 'UNB'
exit_seg = Regexp.new('^UNZ'); tag_exit = 'UNZ'
end
last_seg = nil
loop do
last_seg = segment_list.pop
case last_seg
when /^[A-Z]{3}/
unless last_seg =~ exit_seg
raise "Parse error: #{tag_exit} is not last segment! Found: #{last_seg}"
end
break
when /\n/, /\r\n/, ''
else
warn "WARNING: Data found after #{tag_exit} segment - ignored!"
warn "Found: \'#{last_seg}\'"
end
end
trailer = Segment.parse(ic, last_seg, tag_exit)
err_flag = false
segment_list.each do |seg|
if seg =~ init_seg
warn "ERROR: Another interchange header found in file!"
err_flag = true
end
if seg =~ exit_seg
warn "ERROR: Another interchange trailer found in file!"
err_flag = true
end
end
raise "FATAL ERROR - exiting" if err_flag
case segment_list[0]
when /^UNH/
init_seg = Regexp.new('^UNH')
exit_seg = Regexp.new('^UNT')
group_mode = false
when /^UNG/
init_seg = Regexp.new('^UNG')
exit_seg = Regexp.new('^UNE')
group_mode = true
when /^UIH/
init_seg = Regexp.new('^UIH')
exit_seg = Regexp.new('^UIT')
group_mode = false
else
raise "Expected: UNH, UNG, or UIH. Found: #{segment_list[0]}"
end
while segbuf = segment_list.shift
case segbuf
when init_seg
sub_list = Array.new
sub_list.push segbuf
when exit_seg
sub_list.push segbuf
if group_mode
ic.add( MsgGroup.parse(ic, sub_list), auto_validate )
else
ic.add( Message.parse(ic, sub_list), auto_validate )
end
else
sub_list.push segbuf
end
end
ic.trailer = trailer
ic
end