open(MAIN, "> main.log");
open(SUB1, "> sub1.log");
open(SUB2, "> sub2.log");
open(SUB3, "> sub3.log");
open(SUB4, "> sub4.log");

# monthnum must be in english because it's used to translate log date in apache log files which are always in english
my %monthnum =  ( "Jan","01","jan","01","Feb","02","feb","02","Mar","03","mar","03","Apr","04","apr","04","May","05","may","05","Jun","06","jun","06","Jul","07","jul","07","Aug","08","aug","08","Sep","09","sep","09","Oct","10","oct","10","Nov","11","nov","11","Dec","12","dec","12" );

$good = 1;
$lasttime = 0;
$lasttime1 = 0;
$lasttime2 = 0;
$lasttime3 = 0;
while(<STDIN>){
	# Split DD/Month/YYYY:HH:MM:SS or YYYY-MM-DD HH:MM:SS or MM/DD/YY\tHH:MM:SS
	my $year=0; my $month=0; my $day=0; my $hour=0; my $minute=0; my $second=0;
	if ($_ =~ /(\d\d\d\d)-(\d\d)-(\d\d)\s(\d\d):(\d\d):(\d\d)/) { $year=$1; $month=$2; $day=$3; $hour=$4; $minute=$5; $second=$6; }
	elsif ($_ =~ /\[(\d?\d)[\/:\s](\w+)[\/:\s](\d\d\d\d)[\/:\s](\d\d)[\/:\s](\d\d)[\/:\s](\d\d) /) { $year=$3; $month=$2; $day=$1; $hour=$4; $minute=$5; $second=$6; }
	elsif ($_ =~ /\[\w+ (\w+) (\d?\d) (\d\d)[\/:\s](\d\d)[\/:\s](\d\d) (\d\d\d\d)\]/) { $year=$6; $month=$1; $day=$2; $hour=$3; $minute=$4; $second=$5; }
	elsif ($_ =~ /^(\d\d\d\d+\.\d\d\d) /)
	{
		my $timetime = strftime('%Y-%m-%d-%T', gmtime($1));
		$timetime =~ /(\d\d\d\d)-(\d\d)-(\d\d)-(\d\d):(\d\d):(\d\d)/;
		$year=$1; $month=$2; $day=$3; $hour=$4; $minute=$5; $second=$6;
	}
	if (length $day == 1) { $day = "0".$day; }

	if ($monthnum{$month}) { $month=$monthnum{$month}; }	# Change lib month in num month if necessary

	# Create $timerecord like YYYYMMDDHHMMSS
	$timerecord=int("$year$month$day$hour$minute$second");
	if ($timerecord < $lasttime) {
		$good = 0;
		if ($timerecord >= $lasttime1) {
			print (SUB1);
			$lasttime1 = $timerecord;
		} elsif ($timerecord >= $lasttime2) {
			print (SUB2);
			$lasttime2 = $timerecord;
		} elsif ($timerecord >= $lasttime3) {
			print (SUB3);
			$lasttime3 = $timerecord;
		} else {
			print (SUB4);
		}
	} else {
		print (MAIN);
		$lasttime = $timerecord;
	}
}
if ($good == 1) {
	print "all OK\n";
}

close (MAIN);
close (SUB1);
close (SUB2);
close (SUB3);
close (SUB4);
