/*> do cc -g -I$EPSINC -L$EPSLIB -o %P %F -lcast
 *
 * Extracts the colours used in an AST
 * and their appearance frequency.
 
 * Works on an external (file) representation of the AST.
 
 * Makes use of:
 * an ST to hold colour names
 * an IT to hold frequencies.
 * The ST is accessed via a hash table to speed up searches.
 * The ST is sorted in the last minute,
 * while keeping a permutation table
 * to properly correlate the IT to the ST.
 */

# include <stdio.h>
# include "cast.hh"

/* really, not used, since the file is neither loaded nor saved */
TIOCOLOURS iocolours [] = { OTHERS };

ST* clrs;		/* table of colours found */
IT* frqs;		/* table of frequencies of colours */

main (argc, argv)
     int argc;
     char* argv[];
{
  FILE* fl;		/* file to read */
  char name[BUFSIZ];	/* name of the colour */
  int iname;
  char c;
  int type;
  HT hclrs;
  int i;
  IT* pclrs;		/* permute to sort clrs */

  if (argc == 1)
    fl= stdin;
  if (argc == 2)
    fl= fopen (argv[1], "r");
  if (argc > 2) {
    (void) fprintf (stderr, "usage: %s [file]\n", argv[0]);
    exit (1);
  }
  
  cast_init (iocolours);	/* initialize EPS */
  clrs= STcreate (20, 4, 1);	/* (no dup) table of strings */
  hclrs= STHinit (clrs, 47);	/* hashed access */
  frqs= ITcreate (20, 4, 0);	/* (as is) table of ints */
  for (;;) {
    c= getc (fl);
    if (c == EOF)
      break;			/* end of file: goto print */
    (void) fscanf (fl, "%d", &type);
    c= getc (fl);		/* skip tree information */

				/* hardwired colours */
    if ((c= getc (fl)) == '{') {
      if ((i= STHadd ("#value0", clrs, hclrs, TRUE)) == frqs->size)
	ITadd (1, frqs);
      else
	frqs->data[i]++;
      while ((c= getc (fl)) != '}')
	if (c == '\\')
	  c= getc (fl);
      if ((c= getc (fl)) == '{') {
	if ((i= STHadd ("#value1", clrs, hclrs, TRUE)) == frqs->size)
	  ITadd (1, frqs);
	else
	  frqs->data[i]++;
	while ((c= getc (fl)) != '}')
	  if (c == '\\')
	    c= getc (fl);
	c= getc (fl);
      }
    }

    for (;;) {			/* process colours */
      while (c == ' ' || c == '\t')
	c= getc (fl);
      if (c == '\n')
	break;
				/* load colour name */
      iname= 0;
      do {
	name[iname++]= c;
      } while ((c= getc (fl)) != '{');
      name[iname++]= 0;
				/* add to table, reallocating space */
      if ((i= STHadd (name, clrs, hclrs, FALSE)) == frqs->size)
	ITadd (1, frqs);
      else
	frqs->data[i]++;
      while ((c= getc (fl)) != '}')
	if (c == '\\')
	  c= getc (fl);
      c= getc (fl);		/* skip '}' */
    }
  }
  
  pclrs= STsortP (clrs);	/* sort clrs, keeping a permutation table */
				/* print table */
  for (i= 0; i < clrs->size; i++)
    printf ("%6d  %s\n",
	    frqs->data[pclrs->data[i]],
	    clrs->data[i]);
  exit (0);
}
