Optimized and fixed some functions