require 'socket';require 'yaml';class O;attr_accessor :i,:n,:l
def initialize(n,l);@n,@l,@i=n,l,$d+=1;end;end;def w(i);$m.find{|o|i==o.i};end
def a(r,c);$m.find_all{|o|(!c||c==o.class)&&(!r||r==o.l)};end  
def g(z);a(nil,P).each{|p|p.p(z)};end;def m(z);w(z).n;end;class R<O;attr :e;end
class P<O;attr :s,true;def initialize(n,s);@s=s;super(n,1);end;def p(s)
@s.write(s+E) if @s;end;def y(m);v=w(@l);case m;when /^q/;@s.close;@s=nil
File.open('w','w'){|f|YAML::dump($m,f)};when /^h/;p(m(3))
when /^i/;a(@i,O).each{|o|p(o.n)};when /^c.* (.*)/;g("#{@n}:#{$1}")
when /^g/;a(@l,O).each{|q|q.l=@i};when /^l/;p(v.n)
a(@l,P).each{|x|p(x.n+m(4))if x.s};a(@l,O).each{|x|p(x.n+m(4))}
p(v.e.keys.join("|"));when /(^#{v.e.keys.join('|^')})/;@l=v.e[$1];y('l');else
p "Eh?";end;end;end;E="\r\n";File.open('w'){|f|$m=YAML::load(f)};$d=$m.size
sv=TCPServer.new(0,4000);while k=sv.accept;Thread.new(k){|s|s.write(m(2));s.gets
l=$_.chomp;d=$m.find{|o|P==o.class&&l==o.n};d ? d.s=s : $m<<d=P.new(l,s)
while s.gets;d.y($_.chomp);end;};end