set nick "tclbot"
set user "tclbot"
set real_name "mastah"

set sock ""

proc IRC {} {
 global sock
 if {[eof $sock]} {
  close $sock
  puts "eof"
  return
 }
 if {[catch {set buffer [gets $sock]} r]} {
  close $sock
  puts "err ($r)"
  return
 }
 if {$buffer == "" || $buffer == "\x00"} {return}
 puts "$buffer"
}

proc Connect {ip port {passwd ""}} {
 global nick user real_name
 if {[catch {socket -async $ip $port} sock]} {
  puts "Connection failed, $sock"
  return
 } else {
  puts "CONNECTED! ($sock)"
  fconfigure $sock -blocking 0 -buffering line
  if {$passwd != ""} {
   if {[catch {puts $sock "PASS $passwd"} err]} {
    close $sock
    puts "$err"
    return
   }
   puts "<< PASS $passwd"
  }
  set host [lindex [fconfigure $sock -sockname] 1]
  if {[catch {puts $sock "USER $user $host $ip: $real_name"}]} {
   close $sock
   return
  }
  puts "<< USER $user $host $ip: $real_name"
  puts $sock "NICK $nick"
  puts "<< NICK $nick"
  fileevent $sock readable [list IRC]
 }
}

Connect "192.168.0.2" 6665
