#ifdef IXEMUL_BUG
/*
 * Modified from source code pulled from uunet.uu.net. Original copyright
 * is included here for completeness.
 * 
 * Copyright (c) 1987 Regents of the University of California.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that: (1) source distributions retain this entire copyright
 * notice and comment, and (2) distributions including binaries display
 * the following acknowledgement:  ``This product includes software
 * developed by the University of California, Berkeley and its contributors''
 * in the documentation or other materials provided with the distribution
 * and in all advertising materials mentioning features or use of this
 * software. Neither the name of the University nor the names of its
 * contributors may be used to endorse or promote products derived
 * from this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <stdio.h>
#include <time.h>
#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>

char *mktemp(char *template)
{
    char           ec;
    time_t         rand;
    struct stat    sbuf;
    register char *p;
    register char *save;

    /* get end of string */
    for (p = template; *p ; p++);

    rand = time((time_t *)0);

    /* replace trailing X's with digits */
    while (p >= template && *--p == 'X') {
        *p = rand % 10 + '0';
        rand /= 10;
    }

    /* ensure leading pathname is valid */
    for (save = p + 1; ; p--) {
        if (p <= template)
            break;
        /* have to be able to handle amiga-dos devices (e.g. t:) */
        if (*p == '/' || *p == ':') {
            ec = *(p+1);
            *(p+1) = '\0';
            /* ensure we have a valid directory name */
            if (stat(template,&sbuf))
                return(NULL);
            if ((sbuf.st_mode & S_IFMT) != S_IFDIR)
                return(NULL);
            /* restore / or : */
            *(p+1) = ec;
            break;
        }
    }

    for (;;) {
        if (stat(template,&sbuf) && errno == ENOENT)
            return (template);
        for (p = save; ;) {
            if (!*p)
                return (NULL);
            if (*p == 'z')
                *p++ = 'a';
            else {
                if (isdigit(*p))
                    *p = 'a';
                else
                    ++*p;
                break;
            }
        }
    }

    return (template);
}
#endif
