/*
 * Copyright © 2001 Keith Packard and Carl Worth
 * All Rights Reserved.  See the file COPYING in this directory
 * for licensing information.
 */

autoload PRNG;

int function iswhite (int c)
{
    switch (c) {
    case ' ':
    case '\t':
    case '\n':
    case '\r':
	return 1;
    default:
	return 0;
    }
}

string function word (file in)
{
    string  w = "";
    int	    c;
    
    while ((c = File::getc (in)) != -1)
    {
	w += String::new (c);
	if (!iswhite (c))
	    break;
    }
    if (c == -1)
	return w;
    
    while ((c = File::getc (in)) != -1)
    {
	w += String::new (c);
	if (iswhite (c))
	    break;
    }
    return w;
}

string[*] tags = {
    "B",
    "EM",
    "I",
    "PL",
    "S",
    "TT",
    "U",
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
    "r", "g", "b", "c", "m", "y", "k", "w"
};

typedef tagstack;

typedef struct {
    *tagstack	prev;
    string	tag;
} tagstack;

void function tagfile (file in)
{
    string	w;
    int		d, t;
    *tagstack	stack = 0;

    int function dotag () 
    {
	if (PRNG::randint (100) > 50)
	{
	    int end = PRNG::randint(2);
	    if (stack != 0 && end)
		return -1;
	    return 1;
	}
	return 0;
    }

    int function picktag ()
    {
	return PRNG::randint (dim (tags));
    }

    void function start_tag ()
    {
	stack = reference ((tagstack) {
	    prev = stack,
	    tag = tags[picktag()]
	});
	printf ("<%s>", stack->tag);
    }

    void function end_tag ()
    {
	if (stack)
	{
	    printf ("</%s>", stack->tag);
	    stack = stack->prev;
	}
    }

    for (;;)
    {
	d = dotag ();
	switch (d) {
	case 1:
	    start_tag ();
	    break;
	case 0:
	    break;
	case -1:
	    end_tag ();
	    break;
	}
	string s = word (in);
	if (s == "") break;
	printf ("%s", s);
    }

    while (stack)
	end_tag ();
}

tagfile (stdin);

