var _ = require('lodash'),
  cache = require('gulp-cached'),
  cfValidate = require('../../gulp-plugins/gulp-cf-validate'),
  es = require('event-stream'),
  fs = require('fs-extra'),
  gulp = require('gulp'),
  gulpif = require('gulp-if'),
  gutil = require('gulp-util'),
  matter = require('gray-matter'),
  path = require('path'),
  rename = require('gulp-rename'),
  through = require('through2'),
  util = require("util"),
  url = require('url');


module.exports = function(s3opts,distPath,awsS3) {
  var self = this;

  var templateData = {};

  templateData.s3 = s3opts.aws;
  templateData.s3.prefix = s3opts.prefix;
  var urlString = [awsS3.endpoint.href,path.posix.join(s3opts.aws.bucket,s3opts.prefix)].join('');
  templateData.s3.condensationUrl = url.parse(urlString);

  var stream = es.readable(function(esCount,streamCb) {
    var readable = this;

    var totalCount = 0;
    var lastTotalCount = 0;

    var runStreams = function(globs,options) {
      var s = gulp.src(globs,options)
      .pipe(cache(self.options.projectName+distPath))
      .pipe(gulpif(/\.hbs$/,through.obj(function(file,enc,cb) {
        var m = matter(file.contents.toString());
        var fn = self.handlebars.compile(m.content,{noEscape:true});
        file.contents = new Buffer(fn(_.merge(m.data,templateData),{data: {_file: file}}));
        cb(null,file);
      })))
      .pipe(through.obj(function(file,enc,cb) {
        totalCount = totalCount + 1;
        readable.emit('data',file);
        cb(null,file);
      }));
      s.on('data',function(){});
      s.on('end',function(err) {
        if (lastTotalCount === totalCount) {
          readable.emit('end');
          streamCb();
        }
        else {
          var paths = _.invokeMap(
            self.particleLoader.processablePaths(),
            function() {
              return this+"?(.hbs)";
            }
          );

          lastTotalCount = totalCount;
          runStreams(paths,{base:self.options.root});
        }
      });
    };

    runStreams(
      [
        "particles/cftemplates/**/*.json",
        "particles/cftemplates/**/*.template",
        "particles/cftemplates/**/*.hbs"
      ],
      {cwd:self.options.root,base:self.options.root}
    );

  });


  var parseTemplate = through.obj(function(file,enc,cb) {
    var error;
    if (file.isNull()) {
      //Do Nothing for now
    }
    else {
      try {
        var formatted = JSON.stringify(JSON.parse(file.contents.toString()), null, 2);
        file.contents = new Buffer(formatted);
      }
      catch(e) {
        e.message = "File " + file.path + " is not valid JSON. " + e.message;
        fs.outputFileSync(path.join('condensation_errors',file.path),file.contents);
        error = new gutil.PluginError('build',e);
      }
    }
    cb(error,file);
  });

  var doValidate = function(file) {
    return (file.path.match(/cftemplates[\/\\]/) && (process.env.FORCE_VALIDATE || s3opts.validate))
  }

  stream = stream
  .pipe(gulpif(/\.hbs$/,rename({extname:""})))
  //.pipe(gulpif(/cftemplates[\/\\]/,parseTemplate).on("error",function(e) {this.emit("end"); }))
  .pipe(gulpif(/cftemplates[\/\\]/,parseTemplate))
  .pipe(gulpif(doValidate,cfValidate({region: s3opts.aws.region})))
  .pipe(gulp.dest(distPath))

  return stream;
};

@@ -18,19 +18,21 @@
 lodash')
-,%0A 
+;%0Avar
  cache =
@@ -54,19 +54,21 @@
 cached')
-,%0A 
+;%0Avar
  cfValid
@@ -119,19 +119,21 @@
 lidate')
-,%0A 
+;%0Avar
  es = re
@@ -153,19 +153,21 @@
 stream')
-,%0A 
+;%0Avar
  fs = re
@@ -183,19 +183,21 @@
 -extra')
-,%0A 
+;%0Avar
  gulp = 
@@ -211,19 +211,21 @@
 ('gulp')
-,%0A 
+;%0Avar
  gulpif 
@@ -244,19 +244,21 @@
 ulp-if')
-,%0A 
+;%0Avar
  gutil =
@@ -278,19 +278,21 @@
 p-util')
-,%0A 
+;%0Avar
  matter 
@@ -315,19 +315,21 @@
 matter')
-,%0A 
+;%0Avar
  path = 
@@ -343,19 +343,21 @@
 ('path')
-,%0A 
+;%0Avar
  rename 
@@ -380,19 +380,21 @@
 rename')
-,%0A 
+;%0Avar
  through
@@ -419,15 +419,16 @@
 h2')
-,%0A  uti
+;%0Avar ur
 l = 
@@ -439,21 +439,23 @@
 ire(
-%22util%22),%0A  ur
+'url');%0Avar uti
 l = 
@@ -462,21 +462,22 @@
 require(
-'url'
+%22util%22
 );%0A%0A%0Amod
@@ -572,83 +572,8 @@
  %7B%7D;
-%0A%0A  templateData.s3 = s3opts.aws;%0A  templateData.s3.prefix = s3opts.prefix;
 %0A  v
@@ -667,16 +667,91 @@
 oin('');
+%0A%0A  templateData.s3 = s3opts.aws;%0A  templateData.s3.prefix = s3opts.prefix;
 %0A  templ
@@ -1255,24 +1255,161 @@
 ape:true%7D);%0A
+        var templatePath = file.relative.replace(%22particles/cftemplates/%22,%22%22);%0A        templatePath = templatePath.replace(/%5C.hbs$/,%22%22);%0A
         file
@@ -1434,16 +1434,27 @@
 ffer(fn(
+%0A          
 _.merge(
@@ -1474,16 +1474,27 @@
 teData),
+%0A          
 %7Bdata: %7B
@@ -1508,10 +1508,48 @@
 file
-%7D%7D
+, _templatePath: templatePath%7D%7D%0A        
 ));%0A
@@ -3236,106 +3236,8 @@
 )))%0A
-  //.pipe(gulpif(/cftemplates%5B%5C/%5C%5C%5D/,parseTemplate).on(%22error%22,function(e) %7Bthis.emit(%22end%22); %7D))%0A
   .p

add templatePath to data object