#!/usr/bin/perl -w
use strict;
use warnings;
#use diagnostics;

my $TEXTFILE = defined ($_ = shift) ? $_ : "paratest.txt";

my $I_want_a_trailing_newline = defined ($_ =
  $ENV{"PT_I_want_a_trailing_newline"}) ? $_ : 1;
  
my $Exactly_one_LF_is_para_separator = defined
  ($_ = $ENV{"PT_Exactly_one_LF_is_para_separator"}) ? $_ : 1;

my @paras = ();

my $splitregex = $Exactly_one_LF_is_para_separator ? '(?:^|(?<=\n))\n' :
  '(?:^|(?<=\n))\n+';

open TEXT, "<", "$TEXTFILE";
{ local $/; @paras = split /$splitregex/s, <TEXT>, -1; }
close TEXT;

chomp(@paras) unless $I_want_a_trailing_newline;

for my $x (0..$#paras){
    my $para = $paras[$x];
    print "@{[$x+1]}. paragraph:\n~$para~\n";
    print "\n=== this is not valid ===\n\n" unless 
      $para =~ /^Result\s+Valid/m;

    unless ($para =~ /Result\s+Valid/m) {
	for (split /(?<=\n)/s,$para){
	    print if /^URL/;
	}
    }
}

# if hugh file, don't slurp it completely into memory

open TEXT, "<", "$TEXTFILE";

my ($para, $paracnt) = ("", 0);
while (<TEXT>) {
    if (/^$/ or eof) {
	next if not eof and $para =~ /^\n+$/s and not
	  $Exactly_one_LF_is_para_separator;
	$paracnt++;
	$para .= $_ if eof and not /^$/;
	# if the following is true and $_ eq "\n", then eof did skip the next
	# statement above _and_ we already did print out the last para, so the
	# following code will handle the emty paragraph at EOF and we don't
	# need to redo the loop for the code to be evalueted for the empty
	# paragraph
	my $Already_seen_LFs_in_many_LFs_are_para_separator_mode =
	  $para !~ /^\n+$/s;
	# couldn't avoid this flag variable, since $para will be modified, so
	# that this test can't work after the code
	$para =~ s/^\n+//s;
	chomp $para unless $I_want_a_trailing_newline;
	print "$paracnt. paragraph:\n~$para~\n";
	# do something with $para
	unless ($para =~ /^Result\s+Valid/m) {
	    print "\n=== this is not valid ===\n\n";
	    for (split /(?<=\n)/s,$para){
		print if /^URL/;
	    }
	}
	if (($Already_seen_LFs_in_many_LFs_are_para_separator_mode or
	  $Exactly_one_LF_is_para_separator) and eof and $_ eq "\n") {
	    $para = $_;
	    $_ = "";
	    redo;
	}
	$para = "";
    }
	$para .= $_;
}

close TEXT;
