C code cleanup & thread security