/* el-cheapo sloc program
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <ctype.h>


char *
firstnonblank(char *s)
{
    while (isspace(*s)) ++s;

    return s;
}


main(int argc, char **argv)
{
    FILE *in;
    char *cc = getenv("CC");
    char *cflags = getenv("CFLAGS");
    char line[2000];
    int  sloc, counting;
    int  total = 0;
    int  filelen;
    char *p, *np;
    char *cmdline;
    int  i;


    if ( argc < 2 ) {
	fprintf(stderr, "usage: sloc file [...]\n");
	exit(1);
    }

    if ( cc == 0 ) cc = "cc";
    if ( cflags == 0 ) cflags = "";


    for (i=1; i < argc; i++) {
	counting = sloc = 0;
	if ( access(argv[i], R_OK) == -1 ) {
	    perror(argv[i]);
	    continue;
	}
	filelen = strlen(argv[i]);

	cmdline = alloca(strlen(cc) + strlen(cflags)
				    + strlen(argv[1])
				    + sizeof("-E") + 4);
	sprintf(cmdline, "%s %s -E %s", cc, cflags, argv[i]);


	if ( in = popen(cmdline, "r") ) {
	    while ( fgets(line, sizeof line, in) ) {

		if (line[0] == '#') {
		    p = firstnonblank(line+1);
		    strtoul(p, &np, 10);
		    if (np == p)
			continue;
		    p = firstnonblank(np);
		    if ( *p == '"' )
			counting = (strncmp(p+1, argv[i], filelen) == 0)
					        && (p[1+filelen] == '"');
		}
		else {
		    p = firstnonblank(line);
		    if ( (*p == 0) || (*p == '\n') )
			continue;
		    if (counting)
			sloc++;
		}
	    }
	    pclose(in);
	    printf("%d\t%s\n", sloc, argv[i]);
	    total += sloc;
	}
    }
    if (total != sloc)
	printf("%d\n", total);
    exit(0);
}

