Optimized the code a bit for memory usage