'Replace all instances of variable v with expression E in self,
where v is free in self.'

def replace(self, variable, expression, replace_bound=False, alpha_convert=True):

    if (variable in self.refs):
        if (not replace_bound):
            return self
        else:
            i = self.refs.index(variable)
            if self.consequent:
                consequent = self.consequent.replace(variable, expression, True, alpha_convert)
            else:
                consequent = None
            return DRS(((self.refs[:i] + [expression.variable]) + self.refs[(i + 1):]), [cond.replace(variable, expression, True, alpha_convert) for cond in self.conds], consequent)
    else:
        if alpha_convert:
            for ref in (set(self.refs) & expression.free()):
                newvar = unique_variable(ref)
                newvarex = DrtVariableExpression(newvar)
                i = self.refs.index(ref)
                if self.consequent:
                    consequent = self.consequent.replace(ref, newvarex, True, alpha_convert)
                else:
                    consequent = None
                self = DRS(((self.refs[:i] + [newvar]) + self.refs[(i + 1):]), [cond.replace(ref, newvarex, True, alpha_convert) for cond in self.conds], consequent)
        if self.consequent:
            consequent = self.consequent.replace(variable, expression, replace_bound, alpha_convert)
        else:
            consequent = None
        return DRS(self.refs, [cond.replace(variable, expression, replace_bound, alpha_convert) for cond in self.conds], consequent)
