	#!/usr/bin/perl
	#
	# find relations between next and previous delays between accesses
	#
	
	#define constants
		
	$_Timestamp=0; 	$_Elapsed_Time=1;	$_HTTP_code=2;  
	$_Size=3; 	$_Method=4; 		$_URL=5;
	$_Exp_Date=6;	$_Next_Acc=7; 		$_Cacheable=8;
	$elapsed_time = 0;	#simulation time
	$all_found=0;	#next state found among previous
	$all_notfound=0;	#next state not found among previous
	$history=1;	#depth of history buffer
	for($i=0; $i<12; $i++){$stat[$i]=0;}


   	#open log file
	open(LOG, "+<rez_relations.txt") || die "$0: rez_relations.txt will not open.";
	seek(LOG, 0,2);

	#process files 

       	open(TRACES, "<rez_class_patterns.txt") || die "$file will not open.";
		print "\nOpened: ". $file. "\n";
		seek(TRACES, 0,2); $file_size = tell(TRACES); seek(TRACES, 0,0); 
		
		$pos = tell(TRACES);
		$prev_pos = tell(TRACES);
		$start_time = time();
		while(<TRACES>) { # takes data from $file
			$proc=tell(TRACES)/$file_size;
			print "\rdone: ".$proc." of 1     ";
			#if($proc>0.0025){last;}
			@list = split(" ", $_);
			&det_rel;
		}
		$end_time = time();
		close(TRACES);
		$elapsed_time += ($end_time-$start_time);
	
	print "\nClosed: rez_class_patterns.txt\n";

	print LOG "history:$history all_found: $all_found; all_notfound: $all_notfound\n";
	#for($i=0; $i<$#stat; $i++){print LOG "$i ".$stat[$i]."\n";}
	close(LOG);
	print "\nClosed: rez_relations.txt\n";
	print "\nElapsed: $elapsed_time seconds";


## end ##


#############################################
# algorythms
#############################################


################
# TRANSITIONS  #
################

	sub det_rel{
		my($del, $state, $i, $j, $found);
		for($i=1; $i<$#list; $i++){
			$found=0;
			for($j=$i-1; $j>=0 && $j>=$i-$history; $j--){
				if($list[$i]==$list[$j]){
					$stat[$i-$j]++;
					$found++;
				}
			}
			if(!$found){$stat[0]++; $all_notfound++;}
			else{$all_found++;}
		}
	}

############################################
#subroutine for dumping asoc array to file #
############################################
#store key and value
sub storeaa($$){
	my $a=shift(@_), $f=shift(@_), $key;

	open(DMP, "$f") || die "$0: will not open.";
	
		while (($key, $val) = each (%$a) ){
			print DMP $key." ".$val."\n";
			#print DMP $$a{$key}."\n";
		}

	close DMP;
}

#store just value
sub storeaa_val($$){
	my $a=shift(@_), $f=shift(@_), $key;

	open(DMP, "$f") || die "$0: will not open.";
	
		while (($key, $val) = each (%$a) ){
			print DMP $val."\n";
		}

	close DMP;
}

#load key and value
sub loadaa($$){
	my $a=shift(@_), $f=shift(@_), $key;

	open(DMP, "<$f") || die "$0: will not open.";
	
		while(<DMP>) { # takes data from $file
			@list = split(" ", $_);
			$$a{$list[0]}=$list[1];
		}

	close DMP;
}
