Another rewrite, needs more debugging