 # helper functions
 simple_response = (res, data) ->
   res.setHeader 'Content-Type', 'text/plain'
-  res.end bencode data
-
-compact = (ip, port) -> ip.split('.').concat([port >> 8 & 0xFF, port & 0xFF]).map((c) -> String.fromCharCode c).join('')
+  res.end (bencode.bencode data)
+
+#compact = (ip, port) -> ip.split('.').concat([port >> 8 & 0xFF, port & 0xFF]).map((c) -> String.fromCharCode c)
+compact = (ip, port) -> new Buffer ip.split('.').concat([port >> 8, port & 0xFF])
 
 parse = (qs) ->
   obj = {}

url  = require 'url'
qs   = require 'querystring'
fs   = require 'fs'

# defines
ANNOUNCE_INTERVAL = 60

    # GET requests of interest are:
    #   info_hash, peer_id, port, uploaded, downloaded, left,   <--- REQUIRED
    #   compact, no_peer_id, event, ip, numwant, key, trackerid <--- optional
    info_hash = decodeURLtoHex get_vars['info_hash']
    peer_id = decodeURLtoBinary get_vars['peer_id'], 20
    
    port = parseInt get_vars['port']
    left = parseInt get_vars['left']
    if info_hash == '' or peer_id == '' or isNaN(port) or isNaN(left)
      return simple_response res, {'failure reason': 'Invalid Request'}

    key = 'torrent:' + info_hash

    check_exists = (callback) =>
      @redis.ZCARD (key + ':seeds'), (err, data)=>
        if data != 0
          callback()
        else
          @redis.ZCARD (key + ':peers'), (err, data)=>
            if data != 0
              callback()
            else
              @torrents.findOne {'infohash' : info_hash}, (err, exists) =>
                if exists
                  callback()
                else
                  return simple_response res, {'failure reason': 'This torrent does not exist'}
    check_exists =>
      event = get_vars['event']
      if event == 'stopped' or event == 'paused'
        return simple_response res, 'Nani?'
      
      t = Date.now()
      multi = @redis.multi()
        .ZREMRANGEBYSCORE(key + ':seeds', 0, t - ANNOUNCE_INTERVAL * 6000)
        .ZREMRANGEBYSCORE(key + ':peers', 0, t - ANNOUNCE_INTERVAL * 6000)
      
      ip = get_vars['ip'] #REALLY SHOULD CHECK THIS IS A VALID IP
      ip = req.client.remoteAddress if !ip?
      #ip = process.env['HTTP_X_REAL_IP'] if ip is '127.0.0.1'

      peer_entry = new Buffer 46
      peer_id.copy peer_entry, 0, 0, 20
      compact(ip, port).copy peer_entry, 20, 0, 6
      if ip.length > 15
        console.log "You have major problems. Please seek help"
        return
      for i in [26..45]
        peer_entry[i] = 0
      peer_entry.write ip, 26
      peer_entry.write port.toString(), 41

      suffix = if (left == 0) then ":seeds" else ":peers"
      multi.ZADD key + suffix, t, peer_entry
      
      if event == 'completed' #increment snatch
        @torrents.update {'infohash': info_hash}, {$inc: {'snatches': 1}}
      
      # Output now. Fields are:
      #   interval, complete, incomplete, peers (dict|bin) <--- REQUIRED
