complete rewrite (including debug code)
complete rewrite