Code mostly copied form vanilla...