 # helper functions
 simple_response = (res, data) ->
   res.setHeader 'Content-Type', 'text/plain'
-  res.end (bencode.bencode data)
-
+  res.end (bencode data)
+
+compact = (ip, port) -> (new Buffer ip.split('.').concat([port >> 8, port & 0xFF])).toString 'base64'
 #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])
+#compact = (buf, ip, port) ->
+#  comp = ip.split '.'
+#  for i in [0..3]
+#    buf[20+i] = parseInt(comp[i])
+#  buf[24] = port >> 8
+#  buf[25] = port & 0xFF
 
 parse = (qs) ->
   obj = {}

            'min interval' : MIN_INTERVAL
            'peers'        : peerlist

console.log 'Starting tracker on 127.0.0.1:6969...'
new Tracker 6969

    #   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']
    
    port = parseInt get_vars['port']
    left = parseInt get_vars['left']
    if info_hash == '' or get_vars['peer_id'] == '' or isNaN(port) or isNaN(left)
      return simple_response res, {'failure reason': 'Invalid Request'}

    key = 'torrent:' + info_hash
    key_peer = key + ':peers'
    key_seed = key + ':seeds'

    #get redis etc..
    redis = @redis

    check_exists = (callback) =>
      #callback()
      #return
      redis.ZCARD key_seed, (err, data)=>
        if data != 0
          callback()
        else
          redis.ZCARD key_peer, (err, data)=>
            if data != 0
              callback()
            else
              console.log 'mongo'
              @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_seed, 0, t - ANNOUNCE_INTERVAL * 6000)
        .ZREMRANGEBYSCORE(key_peer, 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 = { 'ip' : ip, 'port' : port, 'peer_id' : get_vars['peer_id'], 'compacted' : compact(ip, port) }

      suffix = if (left == 0) then ":seeds" else ":peers"
      multi.ZADD key + suffix, t, JSON.stringify(peer_entry)
      
      if event == 'completed' #increment snatch
        @torrents.update {'infohash': info_hash}, {$inc: {'snatches': 1}}
