
use strict;
use warnings;

sub msg {
  print STDERR join("\n", @_), "\n";
}

sub fail {
  print STDERR "grep: ";
  msg @_;
  exit 1;
}

my ($ignorecase, $line_number) = ("", 0, 0);
my @a = ();
for (@ARGV) {
  if (/^-(.*)$/) {
    my $p = $1;
    if (length($p) == 0) {
      fail "invalid option: $_";
    }
    for ($p =~ /./gm) {
      if ($_ eq "i") {
        $ignorecase = "i";
      }
      elsif ($_ eq "n") {
        $line_number = 1;
      }
      else {
        fail "bad option: -$_";
      }
    }
  } else {
    push @a, $_;
  }
}
if (@a == 0) {
  msg "Grep (a.kobayashi)", "Usage: grep [options:-in] pattern [file]";
  exit 1;
}
my $pattern = shift @a;
my $regex = "m/$pattern/$ignorecase";
if (@a == 0) {
  while (<STDIN>) {
    if (eval $regex) {
      if ($line_number) {
        print "$.:";
      }
      print;
    }
  }
} else {
  for my $glob (@a) {
    for my $file (glob $glob) {
      open FILE, $file or fail "can't open file: $file";
      while (<FILE>) {
        if (eval $regex) {
          print $file, ":";
          if ($line_number) {
            print "$.:";
          }
          print;
        }
      }
      close FILE;
    }
  }
}
