final touches for main algorithm, fully functional, may add bells and whistles later.