Did some optimizations, but still not fast enough. Need to rethink the algorithm