make the code more robust and replace where possible sprintf with snprintf