       { key, content } = snapshot
 
       content.export (err, result) ->
-        return console.log err  if err
+        return log err  if err
         params = { Key: key, Body: result }
 
+        log "Started uploading #{key} to s3 bucket #{bucket}"
         s3Bucket.upload params, (err) ->
-          return console.log err  if err
-          console.log "#{key} uploaded to s3 bucket #{bucket}"
+          return log err  if err
+          log "Successfully uploaded #{key}to s3 bucket #{bucket}"
 
 start = ->
 
   state = on
 
   # take an initial snapshot
-  latestHeapSnapshot = { content: v8profiler.takeSnapshot(), date: Date.now() }
+  latestHeapSnapshot = { content: v8profiler.takeSnapshot() }
 
   # then take a heap snapshot every minute
   snapshotInterval = setInterval ->
-    latestHeapSnapshot = { content: v8profiler.takeSnapshot(), date: Date.now() }
+    latestHeapSnapshot = { content: v8profiler.takeSnapshot() }
   , 60000
 
   memwatch.on 'leak', handleSnapshots
-  console.log "Started watching possible memory leakage for the process with id #{process.pid}"
+  log "Started watching possible memory leakage for the process with id #{process.pid}"
 
 
 stop = ->

snapshotInterval   = null
latestHeapSnapshot = {}

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.key = "leakedHeapSnapshot.#{leakedHeapSnapshot.date}.heapsnapshot"
  latestHeapSnapshot.key = "latestHeapSnapshot.#{latestHeapSnapshot.date}.heapsnapshot"

  s3Upload [leakedHeapSnapshot, latestHeapSnapshot]


    clearInterval snapshotInterval

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


setup = (options = {}) ->

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

  { AWS_KEY, AWS_SECRET } = options

  unless AWS_KEY or AWS_SECRET
    return log 'Missing S3 credentials'

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

  process.on 'SIGUSR2', ->
