algorithm rewrite works for now, needs some tweaking