#!/usr/bin/perl
use strict;

##
# Script to be used in order to find the range of a 
# value generated in a shader.
# Usage normalrange.pl <shaderSource> <rib> <shaderdir> <valueToBePrinted> <CompliedShaderName>
# Example normalrange.pl ../shader/Bark2.sl ../rib/test.rib ../shader hump Bark2.sdl
#
# Author Hannes Ricklefs - NCCA 2005
##

open SHADER, $ARGV[0]
	or die "Cant open file"; 

open RIB, $ARGV[1]
	or die "Cant open Rib";

open TMP, ">tmp_shader.sl"
	or die "Cant create shader";
	
my $shaderdir = $ARGV[2];
my $printValue = $ARGV[3];
my $shadername = $ARGV[4];


#initialies redicusly high so that the min will be picked up
my $minRange = 10000;
my $maxRange = 0;
my $numValues = 0;
my $average = 0;
	
#-thave to have shader and rib 
#-then change print line in shader and save to tmp_shader
while(<SHADER>) {
	if(/printf/) {
		print TMP "\tprintf (\"%f\\n\",$printValue);\n";
	} else {
		print TMP "$_";
	}
	
}#while shader
#delete the tmp_shader.sl
exec `shaderdl -I$shaderdir tmp_shader.sl`;
exec `cp $shadername $shaderdir/$shadername`;
exec `renderdl $ARGV[1] > values`;

open VALUES, "<values"
	or die "No Values";
	
while (<VALUES>) {
	chomp(my $newline = $_);
	if($newline < $minRange && $newline != 0) {
		$minRange = $newline;
	} elsif ( $newline > $maxRange) {
		$maxRange = $newline;
	}
	
	$average += $newline;
	$numValues++;
	
}
$average = $average/$numValues;
print "MinRange $minRange MaxRange $maxRange Average $average from $numValues values\n";
exec `shaderdl $ARGV[0]`;
exec `cp $shadername $shaderdir/$shadername`;

unlink "tmp_shader.sl";
unlink "values";
unlink "$shadername";

