finished basic algorithm