While looking for solutions with my problem, I discovered this code and it did what I needed. It ran signicantly faster than what I had as well.
But the problem is that I