Changed to realloc. Optimized other code