almost complete rewrite (WIP)