namespace eval ::dcctools {
	namespace export chatInit
	variable cText {}; variable servSock {}
	variable dccSession; array set dccSession [list]

	proc chatInit {client text} {
		variable servSock; variable cText
		if {![info exists ::my-ip]} {return}
		set cText $text
		foreach {a b c d} [split ${::my-ip} .] {}
		set longip [format %u 0x[format %02X%02X%02X%02X $a $b $c $d]]
		set servSock [socket -myaddr ${::my-ip} -server ::dcctools::chatAccept [set port [expr int(rand() * 3976) + 1024]]]
		putserv "PRIVMSG $client :\001DCC CHAT $client $longip $port\001"
	}

	proc chatAccept {sock addr port} {
		variable servSock; variable dccSession
		putlog "Accepting DCC CHAT ($sock) connection from $addr:$port"
		close $servSock; set dccSession($sock) [list $addr $port]
		fconfigure $sock -buffering line
		fileevent $sock writable [list ::dcctools::chatSend $sock]
	}

	proc chatSend {sock} {
		variable dccSession; variable cText
		fileevent $sock writable {}
		puts $sock [join $cText \n]
		putlog "Terminating DCC CHAT ($sock) to [join $dccSession($sock) {:}]"; close $sock
	}
}
package provide dcctools 0.1