Fix memory leak, unitialized vars, typos and follow REP 117