#
# Edit the value of my $time to change how long it takes
# before the image rotates
#
my $time = 45;
#
#
# Nothing else to edit below this line
#

#
#say hello
#
print "Master of Orions 3 graphics MOD\n";
print "End of turn background image rotation utility version 0.92\n";
print "by sm\@inethighway.com\n\n\n";
print "To quit press CTRL + C or simply close this window\n";

#
#the variables
#
my $sdir = "EOTBIR";
my $tdir = "GameDataSets\\Classic_01\\GameAssets\\Common\\Graphics\\UI\\PlayingGame";
my $npic = "pic_waitingbkgd.png";
my ($file, $do, $i);
my @array = ();

#my $ccount = 1;

#
#read image dir and get list of PNGs
#
opendir(DIR, $sdir);
while (defined($file = readdir(DIR))) {
	if ($file =~ /.\.png/i) { 
		push @array, $file;
	}
}
closedir(DIR);

#
#randomize order
#
for ($i = @array; --$i;) {
	my $j = int rand ($i + 1);
	next if $i == $j;
	@array[$i, $j] = @array[$j, $i];
}

#
#copy the files 
#
my $total = @array;
print "\n\nStarting to rotate images ($total total) at a $time second interval.\n";

#my $count = 1;

while () {

	for (@array) { 

		open(IN, "<$sdir\\$_") or die "can't open $sdir\\$_: $!";
		open (OUT, ">$tdir\\$npic") or die "can't open $tdir\\$npic: $!";
		my $blksize = (stat IN)[11] || 16384;
		while($len = sysread IN, $buf, $blksize) {
			if (!defined $len) {
				next if $! =~ /^Interrupted/;
				die "System read error: $!\n";
			}
			$offset = 0;
			while($len) {
				defined($written = syswrite OUT, $buf, $len, $offset) 
					or die "System write error: $!\n";
				$len -= $written;
				$offset += $written;
			};
		}
		close(IN);
		close(OUT);

#		print "$count -> copied $_, waiting $time seconds...\n";
#		$count++;

		sleep $time;
	}

#	print "=> $ccount <= cycles\n\n";
#	$ccount++;

}
