#
# Copyright (c) 2012, USC/ISI
# All rights reserved.
# 
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met: 
# 
# 1. Redistributions of source code must retain the above copyright notice, this
#    list of conditions and the following disclaimer. 
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution. 
# 
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# 

# hsl2rgb($h, $s, $l): convert from HSL to RGB
# $h in [0..360]
# $s in [0..1]
# $l in [0..1]
sub hsl2rgb {
    my ($h,$s,$l) = @_;
    my $c  =(1. - abs(2*$l-1))*$s;
    my $hh = $h/60.;
    my $x  = $c*(1. - abs($hh - 2*int($hh/2.) - 1.));
    my @rgb;
    @rgb = ($c, $x, 0)
	if 0<=$hh && $hh<1;
    @rgb = ($x, $c, 0)
        if 1<=$hh && $hh<2;
    @rgb = (0, $c, $x)
	if 2<=$hh && $hh<3;
    @rgb = (0, $x, $c)
	if 3<=$hh && $hh<4;
    @rgb = ($x, 0, $c)
	if 4<=$hh && $hh<5;
    @rgb = ($c, 0, $x)
	if 5<=$hh && $hh<6;
    my $m = $l-$c/2.;
    @rgb = map { $_ = int(255*($_+$m)) } @rgb;
    return @rgb;
}


# lonlat2rgb($lon, $lat): convert coordinates to RGB triplet
# input:  latitude  in [ -90;  90]
# input:  longitude in [-180; 180]
# output: @rgb
use POSIX qw(fmod);
sub lonlat2rgb {
   my ($lon, $lat) =  @_;
   $lat = -$lat; #north should be dark
   $lon = fmod($lon+3600, 360);
   my ($LATL, $LATH) = (-115, 80); #normalize to this range
   $lat = $LATH if $lat > $LATH;
   $lat = $LATL if $lat < $LATL;
   my @rgb = hsl2rgb($lon, 1, ($lat - $LATL)/($LATH-$LATL));
   return @rgb;
}
