class UnrewriteMiddleware(object):
    """Rewrite our URL back into the logical URL.

    Undoes the effects of a mod_rewrite so that URLs we
    generate look good.  Takes an app to wrap and a dict like:

    {'dispatch.fcgi':'','dispatch.cgi':'dev'}"""
    
    def __init__(self, app, substs):
        self.app = app
        self.substs = substs
        
    def __call__(self, environ, start_response):
        comps = environ['SCRIPT_NAME'].split('/')
        for act in self.substs:
            if act in comps:
                ind = comps.index(act)
                if self.substs[act]:
                    comps[ind] = self.substs[act]
                else:
                    del comps[ind]
        environ['SCRIPT_NAME'] = '/'.join(comps)
        return self.app(environ, start_response)
