complete rewrite v2 probably lots of bugs