full rewriting, almost working