var S3FS = require('s3fs');
var crypto = require('crypto');
var gm = require('graphicsmagick-stream');
var _ = require("lodash");

var options = {};
var s3fs;
var convert;

function S3Storage(opts) {
  if (!opts.bucket) throw new Error('bucket is required');
  if (!opts.secretAccessKey) throw new Error('secretAccessKey is required');
  if (!opts.accessKeyId) throw new Error('accessKeyId is required');
  if (!opts.region) throw new Error('region is required');
  if (!opts.dirname) throw new Error('dirname is required');
  if (!opts.gm) throw new Error('gm is required');
  options = opts;
  s3fs = new S3FS(options.bucket, options);
  convert = gm(options.gm);
}

S3Storage.prototype._handleFile = function(req, file, cb) {
  var fileName;
  if (options.reqfilename) {
    fileName = _.get(req, options.reqfilename);
  }
  else {
    fileName = crypto.randomBytes(20).toString('hex');
  }
  var outStream = s3fs.createWriteStream(options.dirname + '/' + fileName);
  file.stream
    .pipe(convert())
    .pipe(outStream);
  outStream.on('error', cb);
  outStream.on('finish', function() {
    cb(null, {
      size: outStream.bytesWritten,
      key: options.dirname + '/' + fileName,
      location: 'https://' + options.bucket + '.s3.amazonaws.com/' + options.dirname + '/' + fileName
    });
  });
};

S3Storage.prototype._removeFile = function(req, file, cb) {
  s3fs.unlink(file.path, cb);
};

module.exports = function(opts) {
  return new S3Storage(opts);
};

@@ -128,50 +128,8 @@
 );%0A%0A
-var options = %7B%7D;%0Avar s3fs;%0Avar convert;%0A%0A
 func
@@ -529,16 +529,21 @@
 ed');%0A  
+this.
 options 
@@ -552,16 +552,21 @@
 opts;%0A  
+this.
 s3fs = n
@@ -576,19 +576,16 @@
 S3FS(opt
-ion
 s.bucket
@@ -593,17 +593,19 @@
  opt
-ion
 s);%0A  
+this.
 conv
@@ -616,19 +616,16 @@
 = gm(opt
-ion
 s.gm);%0A%7D
@@ -686,16 +686,35 @@
 , cb) %7B%0A
+  var self = this;%0A
   var fi
@@ -727,16 +727,21 @@
 ;%0A  if (
+self.
 options.
@@ -781,16 +781,21 @@
 et(req, 
+self.
 options.
@@ -890,75 +890,112 @@
 var 
-outStream = s3fs.createWriteStream(options.dirname + '/' + fileName
+filePath = self.options.dirname + '/' + fileName;%0A  var outStream = self.s3fs.createWriteStream(filePath
 );%0A 
@@ -1017,16 +1017,21 @@
   .pipe(
+self.
 convert(
@@ -1188,40 +1188,16 @@
 ey: 
-options.dirname + '/' + fileName
+filePath
 ,%0A  
@@ -1219,24 +1219,29 @@
 https://' + 
+self.
 options.buck
@@ -1272,40 +1272,16 @@
 ' + 
-options.dirname + '/' + fileName
+filePath
 %0A   
@@ -1357,16 +1357,21 @@
 cb) %7B%0A  
+this.
 s3fs.unl
@@ -1383,12 +1383,11 @@
 ile.
-path
+key
 , cb

remove global variables