cleaned up algorithm