const DEFAULT_ENCODING = 'UTF8';

var fs = require('fs');
var path = require('path');
var vm = require('vm');
var util = require('util');
var EventEmitter = require('events').EventEmitter;

var _ = require('underscore');

var Preprocessor = function( preprocessor_path, options ){

	// properly inherit from EventEmitter part 1
	EventEmitter.call( this );

	var server = options.server;
	var preprocessor = this;
	var data = this.data = '{}';
	this.path = preprocessor_path;

	// run preprocessor on supplied data
	this.process = function( context, callback ){

		var preprocessing_method = require( this.path );

		try {
			context = preprocessing_method( context );
		} catch( err ){
			server.logger.log('Error in preprocessor: '+ preprocessor.path +' '+ err, 0 );
		} finally {
			if( callback ) callback( context );
		}

	};

	// update the source of the preprocessor
	this.updateSource = function( callback ){

		fs.readFile( this.path, {
			encoding: DEFAULT_ENCODING
		}, function( err, data ){
			if( err ) throw err;
			preprocessor.source = data;
			if( callback ) callback();
		});

	};

	this.updateSource( function(){
		preprocessor.emit( 'ready' );
	});

};

// properly inherit from EventEmitter part 2
util.inherits( Preprocessor, EventEmitter );

module.exports = Preprocessor;
@@ -561,227 +561,42 @@
 %0A%0A%09%09
-var preprocessing_method = require( this.path );%0A%0A%09%09try %7B%0A%09%09%09context = preprocessing_method( context );%0A%09%09%7D catch( err )%7B%0A%09%09%09server.logger.log('Error in preprocessor: '+ preprocessor.path +' '+ err, 0 );%0A%09%09%7D finally %7B%0A%09
+context = this.module( context );%0A
 %09%09if
@@ -628,20 +628,16 @@
 ntext );
-%0A%09%09%7D
 %0A%0A%09%7D;%0A%0A%09
@@ -727,165 +727,81 @@
 %0A%0A%09%09
-fs.readFile( this.path, %7B%0A%09%09%09encoding: DEFAULT_ENCODING%0A%09%09%7D, function( err, data )%7B%0A%09%09%09if( err ) throw err;%0A%09%09%09preprocessor.source = data;%0A%09%09%09if( callback ) 
+delete require.cache%5Bthis.path%5D;%0A%09%09this.module = require( this.path );%0A%09%09
 call
@@ -811,14 +811,8 @@
 k();
-%0A%09%09%7D);
 %0A%0A%09%7D

update preprocessor by clearing require cache