updated algo and fixed bug