added cache
some defensive rewrites