#!/usr/bin/perl

if ($ARGV[0] eq '-b') {
  shift @ARGV;
  $PRINT_BAD = 1;
} elsif ($ARGV[0] eq '-g') {
  shift @ARGV;
  $PRINT_GOOD = 1;
} elsif ($ARGV[0] eq '-s') {
  shift @ARGV;
  $SHORT_FORMAT = 1;
}

my $GOOD;
my $orig;
while (<>) {
  $orig = $_;
  $GOOD = 1;
  if ($IN_POD) {
    if (/^=cut/) { $IN_POD = 0 }
    $GOOD = 0;
    next;
  }

  if (/^__(?:END|DATA)__$/) {
    while (<>) {
      print if $PRINT_BAD;
      $bad++;
    }
    last;
  }

  if (/^=/) { $IN_POD = 1; $GOOD = 0; next }

  s/#.*//;
  $GOOD = 0, next if /^\s*#/;

  $GOOD = 0, next if /^[][\s{}();,]*$/ && ! /\[\s*\]/ && ! /\{\s*\}/;
  $GOOD = 0, next if /^\s*(\}\s*)?else\s*(\{\s*)?$/;
} continue {
  print $orig if $GOOD && $PRINT_GOOD || !$GOOD && $PRINT_BAD;
  $good += $GOOD;
  $bad += !$GOOD;
}

unless ($PRINT_GOOD || $PRINT_BAD) {
  my $total = $good + $bad;
  if ($SHORT_FORMAT) {
    printf "%8d %8d %8d\n", $total, $good, $bad;
  } else {
    print "Total lines: $total\n";
    printf "Code:  %8d (%.2f%%)\n", $good, 100*$good/$total;
    printf "Space: %8d (%.2f%%)\n", $bad, 100*$bad/$total;
    printf "Code/Space: %8.2f\n", $bad ? $good/$bad : 0;
  }
}
