reduced memory usage by replacing for with while.