almost a complete rewrite