/* $Id: tempname.c,v 1.1.1.1 2008/10/28 13:28:21 kiesling Exp $ */

/*
  This file is part of ctalk.
  Copyright © 2005-2008  Robert Kiesling, ctalk@ctalklang.org.
  Permission is granted to copy this software provided that this copyright
  notice is included in all source code modules.

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Lesser General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software Foundation, 
  Inc., 51 Franklin St., Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>

#ifndef MAXLABEL
#define MAXLABEL 255
#endif

char *__rand_ext (void) {

  time_t t;
  int r;
  char buf[MAXLABEL];
  char *s;

  t = time (NULL);
  srand ((unsigned int)t);
  r = rand ();

  sprintf (buf, "%x", r % 0xFFFFFF);

  s = strdup (buf);

  return s;
}

char *__tempname (char *d_path, char *pfx) {

  char pname[FILENAME_MAX];
  char *name_ptr;
  char *rand_ext;
  struct stat statbuf;
  int r;

  while (1) {
    rand_ext = __rand_ext ();
    sprintf (pname, "%s/%s%s", d_path, pfx, rand_ext);
    free (rand_ext);
    if ((r = stat (pname, &statbuf)) != 0) {
      name_ptr = strdup (pname);
      return name_ptr;
    }
  }

  return NULL;
}
