solved the problem. need to find a way to optimize the algoritm