
/* itmpnam.c - Internals for tmpnam() and tmpfile() - ryb */

#include <exec/types.h>
#include <exec/tasks.h>
#include <functions.h>

#define GET_PID() ((ULONG) FindTask (NULL) >> 4)
#define DEFAULT_TEMP_PATH "T:"


/* Code to print a hex number to a buffer without dragging in the printf
   formatting stuff.  This might not really be any better since code that
   uses this for temp file names would likely be using printf functions. */

#ifdef __GNUC__
__inline__
#endif
static void
format_hex (unsigned long x, char **ptr)
{
  unsigned long n;
  char *start, *s;
  char ch;

  start = *ptr;
  for (s = start, n = x; n != 0; n >>= 4)
    s++;
  if (s == start)
    s++;
  *ptr = s;
  while (s > start)
    {
      ch = x & 0x0f;
      if (ch >= 10)
	ch = ch - 10 + 'A';
      else
        ch = ch + '0';
      *--s = ch;
      x >>= 4;
    }
}


/* Generate a unique name for a temporary file.  The format of the file name
   is <PREFIX><PATH><task>.<count>, where <task> is a 1 to 7 digit hex number
   unique to each task and <count> is a 1 to 8 digit hex number unique to
   each call.  *COUNT should be initialized to zero before the first call.
   BUF must be large enough to hold the result.  The file names (not
   including PATH) would work in a file system that restricts file names
   to seven characters with a three character extension after a dot as long
   as PREFIX is one character and *COUNT is kept below 4095. */

char *
__tmpnam (char *buf, const char *path, const char *prefix, int *counter)
{
  char *s;
  const char *t;

  s = buf;
  t = path;
  while (*t != '\0')
    *s++ = *t++; 
  t = prefix;
  while (*t != '\0')
    *s++ = *t++; 
  /* The size of the Task structure is much more than 16 bytes so N below
     is still unique to each task. */
  format_hex (GET_PID (), &s);
  *s++ = '.';
  /* Pre-increment so that *COUNTER can be zero initially. */
  format_hex (++*counter, &s);
  *s++ = '\0';
  return buf;
}


/* Function to get path prefix for temporary files.  Could be changed to
   check an environment variable. */

char *
__get_temp_path (void)
{
  return DEFAULT_TEMP_PATH;
}
