namespace eval csc {
  package require Tcl 8.3
  package require eggdrop 1.6
  package require http
  variable version "0.1"

  bind pub - .csc [namespace current]::pub
  bind pub - !csc [namespace current]::pub
  bind pub - `csc [namespace current]::pub

  proc pub {nick uhost hand chan text} {
    if {![llength [set check [lindex [split $text] 0]]]} {
      putserv "PRIVMSG $chan :Usage: .csc <channel>"
      return
    }

    set check [string range $check 1 end]
    set url "http://cservice.undernet.org/live/check_app.php?name=$check"
    set result [read $url]
    puthelp "PRIVMSG $chan :#$check $result"
  }

  proc read {url} {
    set token [::http::geturl $url]
    set content [::http::data $token]
    ::http::cleanup $content

    regsub -all {<[^>]*>} $content { } content

    foreach line [split $content \n] {
      if {![llength $line] || [string match "*CService*" $line]} continue
      set message $line
      break
    }

    if {![info exists message]} {
      upvar #0 $token state
      foreach {name value} $state(meta) {
        if {![regexp -nocase ^location$ $name]} continue
        set url "http://cservice.undernet.org/live/$value"
        break
      }
      redirect $url
      } else {
      return $message
    }
  }

  proc redirect {url} {
    set token [::http::geturl $url]
    set content [::http::data $token]
    ::http::cleanup $content

    set top "<table border=0 cellspacing=0 cellpadding=3>"
    set bottom "<script language=\"JavaScript1.2\">"
    set tosave [string range $content [set f [string first $top $content]] [string first $bottom $content $f]] 

    regsub -all {<[^>]*>} $tosave {} tosave
    regsub -all {&nbsp;} $tosave {} tosave
    regsub -all {CHANNEL SERVICE APPLICATIONS - VIEW APPLICATION} $tosave {} tosave
    regsub -all {Check another application} $tosave {} tosave
    regsub -all {Add an Objection for that application} $tosave {} tosave
    regsub -all {note: you can only post ONE objection per channel.} $tosave {} tosave
    regsub -all {You must be logged in in order to post objections} $tosave {} tosave
    regsub -all {Click here to log in} $tosave {} tosave
    regsub -all {Current Objections} $tosave {} tosave
    regsub -all {<} $tosave {} tosave
    regsub -all {:} $tosave {} tosave
    
    

    set id "0"
	set number 1
    foreach line [split $tosave \n] {
		set linie($number) "$line"; incr number
        }
		set posted [lrange $linie(3) 2 end]
		set user [lindex $linie(4) [expr [lsearch $linie(4) user]+1]]
		set status [lindex $linie(5) [expr [lsearch $linie(5) status]+1]]
		return "Stage: $status | Applicant: $user | Submitted on: $posted"
	
  }

  putlog "cservice.tcl v$version loaded"
}