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

/*
 * getpty()
 *
 * Allocate a pty.  As a side effect, the external character
 * array "line" contains the name of the slave side.
 *
 * Returns the file descriptor of the opened pty.
 */
static char Xline[] = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
char *line = Xline;

int
getpty(ptynum)
int *ptynum;
{
        register int p;
        register char *cp, *p1, *p2;
        register int i;

        (void) sprintf(line, "/dev/ptyXX");
        p1 = &line[8];
        p2 = &line[9];
        for (cp = "pqrstuvwxyzPQRST"; *cp; cp++) {
                struct stat stb;

                *p1 = *cp;
                *p2 = '0';
                /*
                 * This stat() check is just to keep us from
                 * looping through all 256 combinations if there
                 * aren't that many ptys available.
                 */
		printf("Trying to stat pty %s\n", line);
                if (stat(line, &stb) < 0) {
			printf("Stat failed\n");
                        break;
		}
                for (i = 0; i < 16; i++) {
                        *p2 = "0123456789abcdef"[i];
			printf("%s: ", line);
                        p = open(line, 2);
                        if (p > 0) {
				printf("free and open\n");
                        } else {
				printf("%s\n", strerror(errno));
			}
                }
        }
        return(-1);
}

main ()
{
  printf("Returned PTY: %d\n", getpty(0));
}
