#!/usr/bin/perl
# Script by Michael Howe <michael.howe@worc.ox.ac.uk> to count the number of
# lines of code and comments in files.
# Usage: linecount <file1> <file2> ... <fileN>
# $Id: linecount 345 2010-07-04 18:08:57Z michael@MICHAELHOWE.ORG $
use strict;
use warnings;
use Getopt::Long;

my $count = 0;
my $lines = 0;
my $comment = 0;
my $blank = 0;
my $ispod = 0;
my $files = 0;
my $lang = 'perl';
my $help = 0;

my $result = GetOptions("l|lang=s" => \$lang,
                        "h|help" => \$help );

if( $help ){
    print "Usage: $0 [--lang PHP] <file1> [<file2>...<fileN>]

    Counts number of lines in file(s), and analyzes as code/whitespace/comment.
";
    exit 0;
}

my $normalcomment;
my $startpod;
my $endpod;
my $blankrx;
if( $lang eq 'PHP' ){
    $normalcomment = qr{^\s*(?:#[^!]|//)}o;
    $startpod = qr{^\s*/\*}o;
    $endpod = qr{\*/}o;
} else {
    $normalcomment = qr{^\s*#[^!]}o;
    $startpod = qr{^=.*$}o;
    $endpod = qr{^=cut$}o;
}
# Empty line:
$blankrx = qr{^\s*$}o;

foreach ( @ARGV ) {
	open( FH, "<", $_ ) or warn "Can't open $_: $!" and next;
	while ( <FH> ) {
		chomp;
		if ( $ispod ) {
			$comment++;
			if ( m{$endpod}o ) {
				$ispod = 0;
			}
		} elsif ( m{$startpod} ) {
			$ispod = 1;
			$comment++;
		} elsif ( m{$normalcomment} ) {
			$comment++;
		} elsif ( m{$blankrx} ) {
			$blank++;
		} 
		$lines++;
	}
	$ispod = 0;
	close FH;
	$files++;
}

my $codelines = $lines - $comment - $blank;
my $codepercent =  ( $codelines / $lines ) * 100;
my $blankpercent = ( $blank / $lines ) * 100;
my $commentpercent = ( $comment / $lines ) * 100;
print "Using language: $lang\n";
printf( "Files: %d\nLines: %d\nComments: %d (%.1f%%)\nBlank: %d (%.1f%%)\nCode: %d (%.1f%%)\n", $files, $lines, $comment, $commentpercent, $blank, $blankpercent, $codelines, $codepercent );


