What drupal function do I use to rename files when saving nodes programatically?
Drupal uses the file_create_filename() function to do that, you can call it like this:

$basename = drupal_basename($local_path);
$directory = drupal_dirname($local_path);
$local_path = file_create_filename($basename, $directory);

$file = new stdClass();
$file-&gt;filename = drupal_basename($local_path);
$file-&gt;filepath = $local_path;
// etc...