#!/usr/bin/perl

use Math::Round qw(round);
use CGI;
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use strict;
use warnings;

my $q = CGI->new;
print $q->header;


#print "Initial Color: ";
#my $c1 = <STDIN>;
#print "Final Color: ";
#my $c2 = <STDIN>;
#print "Number of Tween Colors: ";
#my $steps = <STDIN>;

#chomp $c1;
#chomp $c2;
#chomp $steps;

my $initial = join(";",( $q->param('r1'), $q->param('g1'), $q->param('b1')));
my $final = join(";", ($q->param('r2'), $q->param('g2'), $q->param('b2') ));
my $steps = $q->param('steps');

#if (@initial && @final)
#{
	&getColors($initial, $final, $steps);
#}

print <<EOF;
<br>
<center>
<fieldset>
<form action="colorfader.pl" method="POST">
<table border="0">
	<tr>
		<td></td>
		<td>R</td>
		<td>G</td>
		<td>B</td>
	</tr>
	<tr>
		<td><b>Initial Color</b></td>
		<td><input type="text" maxlength="3" name="r1" size="3"></td>
		<td><input type="text" maxlength="3" name="g1" size="3"></td>
		<td><input type="text" maxlength="3" name="b1" size="3"></td>
	</tr>
	<tr>
		<td><b>Final Color</b></td>
		<td><input type="text" maxlength="3" name="r2" size="3"></td>
		<td><input type="text" maxlength="3" name="g2" size="3"></td>
		<td><input type="text" maxlength="3" name="b2" size="3"></td>
	</tr>
</table>
Number of Tween Colors: <input type="text" name="steps" size="3">
<input type="submit" value="Tween">
</form>
</fieldset></center>
EOF


# (initial, final, steps)
sub getColors
{
	my @initial = split(/;/, $_[0]);
	my @final = split(/;/, $_[1]);
	my $steps = $_[2];
	
	for (my $i = 0; $i < 3; $i++)
	{
		if ($initial[$i] > 255 || $initial[$i] < 0 || $final[$i] > 255 || $final[$i] < 0)
		{
			print "All values are 0-255\n";
			return;
		}
	}
	
	my @mids;
	#add round() back in;
	my $midrangeR = ($final[0] - $initial[0])/($steps + 1);
	my $midrangeG = ($final[1] - $initial[1])/($steps + 1);
	my $midrangeB = ($final[2] - $initial[2])/($steps + 1);

	for (my $j = 0; $j < $steps; $j++)
	{
		$mids[$j][0] = round($initial[0] + ($midrangeR * ($j + 1)));
		$mids[$j][1] = round($initial[1] + ($midrangeG * ($j + 1)));
		$mids[$j][2] = round($initial[2] + ($midrangeB * ($j + 1)));
	}
	
	for (my $i = 0; $i < $steps; $i++)
	{
		print "#", $i + 1, ": ";
		for (my $j = 0; $j < 3; $j++)
		{
			print $mids[$i][$j], " "; 
		}
		#print "\n\<font color=\"rgb(,", $mids[$i][0], ",", $mids[$i][1], ",", $mids[$i][2], ")\"\>";
		#print "\x{2588}\</font\>";
		print "\n\<br\>\n";
	}
}
