/* Though documented in the Manx manual, mktemp is not in the C library.
   Unix documents this to take a "pathname with 6 trailing 'X' characters
   which will be replaced with the current pid and a single letter."

   Since our "pids" are always small, I use a "generation" number, (like NFS)
   to add two more cycling bytes in the name to reduce filename collisions.
   so we have not 26 possibilities, but 256 * 26.
*/
#include <libraries/dosextens.h>
#include <stdio.h>

char *mktemp(char *origs)
{
    FILE *fp;
    char pidbuf[12], *pb = pidbuf, *s = origs;
    static int lastletter = 'z';
    static int generation = 0;
    int i;
    BPTR lk;

    if (!s) return (NULL);
    sprintf (pidbuf, "%02d%02x", getpid(), (generation & 0xFF));
    
    while (*s) {
	if (*s == 'X') {
	    if (!*pb) break;	/* We've run out of "pid" and found an 'X' */
	    *s = *pb++;		/* Drop in the "pid" over 'X's */
	}
        s++;
    }

    if (!*s) return(NULL);	/* Not enough 'X's */
    *(s + 1) = '\0';		/* Chop off remaining 'X's and anything else. */
    i = lastletter;
    for (;;) {
	if (++lastletter > 'z') {
	    lastletter = 'a';
	    generation++;
	}
	*s = lastletter;
	if (!(lk = Lock(origs, ACCESS_READ)))
	    return(origs);
	else
	    UnLock(lk);

	if (i == lastletter) return (NULL);
    }
}
