#!/usr/bin/perl

sub usage 
{
   printf "\nUsage:\n";
   printf "   mlgrep.pl [-v] <pattern>\n";
   printf "where -v means \"print non-matching entries\" (= invert search)\n";
}


# program's main code

my $invert = "";
my $pattern_to_grep = "";

if ($#ARGV < 0)
{
   printf "need something to grep...\n";
   usage();
   exit 1;
}

if ($ARGV[0] =~ /^-v$/)
{
   if ($#ARGV < 1)
   {
      printf "first arg says \"-v\" (=invert), but no pattern given.\n";
      printf "need something to grep...\n";
      usage();
      exit 1;
   }

   $invert = 1;
   $pattern_to_grep = $ARGV[1];
}
else  # the first arg is our pattern
{
   $pattern_to_grep = $ARGV[0];
}

my @entry;
my $print_this;

if ($invert == 1)
{
   $print_this = 1;
}
else
{
   $print_this = "";
}


while (<STDIN>)
{
   if (!(/^$/))
   {
      # non-empty line
      push @entry,$_;

      if ($_ =~ /$pattern_to_grep/)
      {
         if ($invert == 1)
         {
            $print_this = "";
         }
         else
         {
            $print_this = 1;
         }
      }
   }
   else
   {
      # empty line (separator)
      if ($#entry + 1 > 0)
      {
         if ($print_this == 1)
         {
            my $line;

            # the array has accumulated some data = is non-empty
            while ($line = shift(@entry))
            {
               print $line;
            }

            if ($invert != 1)
            {
               $print_this = "";
            }
            print "\n";  # empty line = separator between entries
         }
         else
         {
            @entry = ();  # clear the array

            if ($invert == 1)
            {
               $print_this = 1;
            }
         }
      }
      # else the array is empty, do nothing
   }
}

