 snapshotInterval   = null
 latestHeapSnapshot = {}
 
+log = (string) -> console.log "[MemoryLeakWatcher] #{string}"
+
+
 handleSnapshots = (info) ->
 
-  leakedHeapSnapshot = { content: v8profiler.takeSnapshot(), date: Date.now() }
-  console.log 'Memory leakage detected ', info
-  console.log 'Snapshot headers: Leaked snapshot:', leakedHeapSnapshot.content.getHeader(), 'Latest snapshot before the leak:', latestHeapSnapshot.content.getHeader()
-  console.log 'Leaked snapshot compared to the latest snapshot: ', latestHeapSnapshot.content.compare leakedHeapSnapshot.content
+  leakedHeapSnapshot = { content: v8profiler.takeSnapshot() }
+  log 'Memory leakage detected ', info
+  log 'Snapshot headers: Leaked snapshot:', leakedHeapSnapshot.content.getHeader(), 'Latest snapshot before the leak:', latestHeapSnapshot.content.getHeader()
 
-  leakedHeapSnapshot.key = "leakedHeapSnapshot.#{leakedHeapSnapshot.date}.heapsnapshot"
-  latestHeapSnapshot.key = "latestHeapSnapshot.#{latestHeapSnapshot.date}.heapsnapshot"
+  date                   = Date.now()
+  leakedHeapSnapshot.key = "leakedHeapSnapshot.#{date}.heapsnapshot"
+  latestHeapSnapshot.key = "latestHeapSnapshot.#{date}.heapsnapshot"
 
   s3Upload [leakedHeapSnapshot, latestHeapSnapshot]
 

    clearInterval snapshotInterval

  memwatch.removeListener 'leak', handleSnapshots
  console.log "Stopped watching possible memory leakage for the process with id #{process.pid}"


setup = (options = {}) ->

  console.log "To start/stop watching memory profiling send SIGUSR2 to PID #{process.pid}"

  { AWS_KEY, AWS_SECRET } = options
  AWS.config.update { accessKeyId: AWS_KEY, secretAccessKey: AWS_SECRET }

  process.on 'SIGUSR2', ->

      { key, content } = snapshot

      content.export (err, result) ->
        return log err  if err
        params = { Key: key, Body: result }

        log "Started uploading #{key} to s3 bucket #{bucket}"
        s3Bucket.upload params, (err) ->
          return log err  if err
          log "Successfully uploaded #{key}to s3 bucket #{bucket}"

start = ->

  state = on

  # take an initial snapshot
  latestHeapSnapshot = { content: v8profiler.takeSnapshot() }

  # then take a heap snapshot every minute
  snapshotInterval = setInterval ->
    latestHeapSnapshot = { content: v8profiler.takeSnapshot() }
  , 60000

  memwatch.on 'leak', handleSnapshots
  log "Started watching possible memory leakage for the process with id #{process.pid}"


stop = ->
