class DEBUGGER__::Client

def connect

def connect
  pre_commands = (CONFIG[:commands] || '').split(';;')
  trap(:SIGINT){
    send "pause"
  }
  begin
    trap(:SIGWINCH){
      @width = IO.console_size[1]
    }
  rescue ArgumentError
    @width = 80
  end
  while line = @s.gets
    p recv: line if $VERBOSE
    case line
    when /^out (.*)/
      puts "#{$1}"
    when /^input (.+)/
      pid = $1
      @multi_process = true if @pid && @pid != pid
      @pid = pid
      prev_trap = trap(:SIGINT, 'DEFAULT')
      begin
        if pre_commands.empty?
          line = readline
        else
          line = pre_commands.shift
          puts "(rdbg:remote:command) #{line}"
        end
      rescue Interrupt
        retry
      ensure
        trap(:SIGINT, prev_trap)
      end
      line = (line || 'quit').strip
      send "command #{pid} #{@width} #{line}"
    when /^ask (\d+) (.*)/
      pid = $1
      print $2
      send "answer #{pid} #{$stdin.gets || ''}"
    when /^quit/
      raise 'quit'
    else
      puts "(unknown) #{line.inspect}"
    end
  end
rescue => e
  STDERR.puts "disconnected (#{e})"
  exit
ensure
  deactivate
end