     clearInterval snapshotInterval
 
   memwatch.removeListener 'leak', handleSnapshots
-  console.log "Stopped watching possible memory leakage for the process with id #{process.pid}"
+  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}"
+  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', ->

      { key, content } = snapshot

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

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

start = ->

  state = on

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

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

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


stop = ->

snapshotInterval   = null
latestHeapSnapshot = {}

log = (string) -> console.log "[MemoryLeakWatcher] #{string}"


handleSnapshots = (info) ->

  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()

  date                   = Date.now()
  leakedHeapSnapshot.key = "leakedHeapSnapshot.#{date}.heapsnapshot"
  latestHeapSnapshot.key = "latestHeapSnapshot.#{date}.heapsnapshot"

  s3Upload [leakedHeapSnapshot, latestHeapSnapshot]

