fixing up algorithm a bit