Added malloc_s and, code improvements and small fixes