Prettify code
Safety checks on memory allocation and memory leaks fix