# File lib/edi4r/edifact.rb, line 478
    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 )
      # Remember to update ndb to SV4-1 now if d0076 of UNB/S001 tells so

      # Deal with 'trash' after UNZ

      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}/ # Segment tag?
          unless last_seg =~ exit_seg
            raise "Parse error: #{tag_exit} is not last segment! Found: #{last_seg}"
          end
          break
        when /\n/, /\r\n/, ''
          # ignore linebreaks at end of file, do not warn.
        else
          warn "WARNING: Data found after #{tag_exit} segment - ignored!"
          warn "Found: \'#{last_seg}\'"
        end
      end
      trailer = Segment.parse(ic, last_seg, tag_exit)

      # Assure that there is only one UNB/UNZ or UIB/UIZ

      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

      # OK, ready to deal with content now:

      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/ # There is no 'UIG'!
        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 # while

      # Finally add the trailer from the originally read data,
      # thereby overwriting the temporary interchange trailer.
      # Note that the temporary trailer got modified by add()ing 
      # to the interchange.
      ic.trailer = trailer
      ic
    end