var http = require('../http'),
    urls = require('../urls'),
    escaperoute = require('escaperoute'),
    shortcuts = require('../shortcuts'),
    renderToResponse = shortcuts.renderToResponse,
    qs = require('querystring');

exports.BaseMiddleware = {
    'processRequest':function(req) {
        var rootUrlConf = urls.getRoot(),
            match = rootUrlConf.match(req.pathname);
        req.pushProcessRequest(function (req) {
            match(req);
        });
        req.attemptContinue();
    },
    'processResponse':function(req) {
        req.end();
    },
    'processException':function(req) {
        var error = null;
        try {
            error = req.errors.pop();
        } catch(err) {
            
        }
        if(error instanceof escaperoute.NoMatch) {
            req.respond(new http.Http404("Not Found"));
        } else {
            req.respond(new http.Http500("Internal Server Error"));
        }
    },
};

exports.ProcessUrlEncodedMiddleware = {
    'processRequest':function(req) {
        if(req.nodeRequest.headers['content-type'] === 'application/x-www-form-urlencoded') {
            req.nodeRequest.on('data', function(data) {
                data = unescape(data.toString('utf8'));
                req[req.method] = qs.parse(data);
                req.attemptContinue();
            });
        } else {
            req.attemptContinue();
        }
    }
};

exports.DebugMiddleware = {
    'processException':function(req) {
        var error = req.errors.pop(),
            templateName = err instanceof escaperoute.NoMatch ? 'core/debug404.html' : 'core/debug500.html';

        renderToResponse(req)('core/debug404.html', {
            'error':error,
            'request':request 
        });
    },
};

@@ -1463,32 +1463,70 @@
 function(req) %7B%0A
+        if(this.settings.debug) %7B%0A    
         var erro
@@ -1544,15 +1544,21 @@
 ors.
-pop(),%0A
+shift(),%0A    
     
@@ -1583,16 +1583,18 @@
 me = err
+or
  instanc
@@ -1669,24 +1669,28 @@
 ';%0A%0A        
+    
 renderToResp
@@ -1703,98 +1703,283 @@
 eq)(
-'core/debug404.html', %7B%0A            'error':error,%0A            'request':request %0A
+templateName, %7B%0A                'error':error,%0A                'stack':error.stack ? error.stack.split('%5Cn') : %5B''%5D,%0A                'urlpatterns':error.urlpatterns,%0A                'request':req,%0A                'settings':require('../settings').getAllValues(), %0A   
         
 %7D);%0A
@@ -1970,26 +1970,89 @@
 %0A           
+ 
 %7D);%0A
+        %7D else %7B%0A            req.attemptContinue();%0A        %7D%0A
     %7D,%0A%7D;%0A

fix debug middleware error handling