#!/usr/local/bin/perl
# Author: Tom M
# This program counts the number of lines of code, excluding
# comment characters and whitespace.  
# Usage:
# LOC [-c commentchar] filename
# The default comment character is "//"


$commentChar = "\/\/";  # the default comment is //
$total = 0; 		# the total count of all files LOC

if ( $ARGV == 1 ) {
    print ( "Usage: LOC [-c commentcharacter] filename\n" );
    exit( 1 );
}

# get filename from each argurment on command line
foreach $file (@ARGV) {

    print ( "$file\n" );
    $flag = 0;		#this flag is set if there is a command line comment

    if ( $nextComment ) { 	#change default comment to command line comment
	$commentChar = $file;
	$flag = 1;
	$nextComment = 0;
    }

    if ( $file eq "-c" ) {	#a comment is given on command line...
	$nextComment = 1;
	$flag = 1;
    }

    if ( $flag == 0   ) {
	open ( LOC, $file ) ||
	    die ("Negative.  $program does not exist." );
	$line = ;
	$count = 0;

	while ( $line ne "" ) {
	    chop ($line ) ;
	    $line =~ s/\s//g;  #remove all whitespace

	    if ( $line =~ /^\/\*/ ) {   #if comment is /*, stop counting...
		$state = 1;
	    }

	    if ( $line =~ /^\*\// || $line =~ /\*\/$/ ) {     #resume counting
		$state = 0;
		$count--;
	    }

	    #if it's not a comment or a blank line, count this as a LOC
	    if ( $line eq "" || $line =~ /^$commentChar/ || $state == 1  ) { }
	    else {
		#print ( "$line\n" );
		$count = $count + 1;
	    }

	    $line = ;
	}
	print ( "....Total lines of code: $count \n") ;
	$total += $count;
    }

}
    print( "-----------------------------\n" );
    print ("Total LOC :              $total\n" );