Some code and memory optimizations (still some work to do)