/*
 cLIeNUX tally

NAME
tally -  count occurances of each possible byte value in files

DESCRIPTION
 Handy for designing keymaps, possibly for other investigations.  tally
runs pretty quickly. What tally does is very simple and easy for a
computer. Note that tally itself doesn't uncompress or unarchive. All args
to tally are files to be processed. Shell expansion applies. Output is to
stdout. This first version doesn't use stdin. So-o, can be used with
advantage like...
	tally hello.c
	tally `find . -name "*.[ch]" ` | sort -nr |less 
et cetera. The tab-delimited fields in tally's output are...
     occurances count,  which byte #,  byte as ASCII,  percentage
...which facilitates sorting by prevalence.

SEE ALSO; ascii, wc

BUGS  see below
*/


/* from   see open   */
#include 
#include 
#include 

#include 

int i, j, fd, errno, /* phonetic past tense of read */ red;
long  count[256];
char buffer[4096];	/* I get the impression Linux likes this size */	
float total;


void report(){		/*  output results to stdout (i.e. print) */ 
for (i = 0; i < 256 ; i++)		/* one-liner loop for a total */
	total = total + (float)count[i];

for (i = 0; i < 256 ; i++)		/* for each possible byte value */
	{ 
	printf ( "%d\t%d\t" , count[i], i );	
	if ( isprint(i))			/* output ASCII or 
						unprintables as  [number] */
		{ printf ( "%c\t", i );
		}
	else 	{ printf("[%d]\t", i);
		}
	printf("%2.2f %%", ( (float) count[i] / total ) * 100.0 );
	printf("\n");
	}
}


int main (int argc, char  *argv[])	/* program starts running here. */
{
for ( i = 1 ; i < argc ; i++)		/* all args are files, no switches */
	{
	fd = open( argv[i], O_RDONLY );
	red = -2 ;
	while ( red )			/* buffer IO sans libc. pththtp  */
		{
		red = read(fd, buffer, 4096);
		if ( red == -1 )
			break ;
		for (j = 0 ; j < red ; j++)
			count[buffer[j]]++ ;   /* the crux of the biscuit, 
						increment a byte's count  */ 	
		}
	} /* end files loop */

report();	/* output results to stdout */
return 0; 	/* turn off some compiler warning noise */
} 		/* end of main, end of program code  

RIGHTS
Copyright 1999 Richard Allen Hohensee
This file and the tally executable are released for redistribution only as 
part of an intact entire cLIeNUX Core.
*/