#!/usr/bin/perl
#
# Copyright Robin * Slomkowski
# Wed Oct 10 20:43:02 PDT 2001 - Thu Oct 11 15:12:36 PDT 2001
# 0.2
#
# You are free to use this code however you like, as long
# as you keep the Copyright, somewhere with it.  Sell it,
# modify it, whatever you like.
#
# basically you can set xterm parameters such as background, foreground
# font, and title, by passing the argument to this script.  If you don't
# pass it anything it will just set some random values for your xterm.
#
# I use this to colour code my xterms so I have more connection with
# which one I am using.
#

use strict ;

main {

my ($VERSION, $ESC, $BEL ) ;
my ($MAX_COLOUR) ;

$VERSION         = "0.4" ;
$ESC             = "\033" ;
$BEL             = "\07" ;

$MAX_COLOUR = 16 ;

my (%option) ;

%option = (
        "title" => 2,
        "T"     => 2,
        "n"     => 1,
        "fg"    => 10,
        "bg"    => 11,
        "cr"    => 12,
        "mousefg"=> 13,
        "tekfg" => 15,
        "tekbg" => 16,
        "hc"    => 17,
        "font"  => 50,
        "fn"    => 50
);

#
# Main
#

if ( $#ARGV == -1 ) {
        $ARGV[0] = 'bg' ;
        $ARGV[1] = random_colour() ;
        $ARGV[2] = 'fg';
        $ARGV[3] = text_colour($ARGV[1]) ;
} elsif ($ARGV[0] eq '--print') {
        shift @ARGV ;
        my ( $colour) ;
        $colour = random_colour() ;
        print '-bg ' . $colour . ' -fg ' . text_colour($colour) . "\n" ;
}



while ( $#ARGV >= 1 ) {
        $ARGV[0] =~ s/^-+// ;
        if ( $option{"$ARGV[0]"} ) {
                printf("$ESC]%d;%s$BEL", $option{"$ARGV[0]"}, $ARGV[1] );
                shift @ARGV ;
                shift @ARGV ;
        }
}

if ( $#ARGV == 0 ) {
        usage() ;
}

#
# functions
# 

sub usage {
        print "$0: option value [option value] .....\n"

}

sub format_colour {
        return "RGB:$_[0]/$_[1]/$_[2]" ;
}

sub random_colour {
        my ($Red, $Green, $Blue, $return ) ;
        $Red =  sprintf("%x", rand($MAX_COLOUR) ) ;
        $Green =  sprintf("%x", rand($MAX_COLOUR) ) ;
        $Blue =  sprintf("%x", rand($MAX_COLOUR) ) ;
        $return = format_colour( $Red, $Green, $Blue) ;
        return $return ;
}

sub text_colour {
        my ($background, @background_values, $background_value) ;
        my ($return) ;
        $background = shift @_ ;
        $background =~ s/^RGB:// ;
        @background_values = split '/', "$background"  ;
        $background_value = hex($background_values[0]) +
                            hex($background_values[1]) +
                            hex($background_values[2]) ;
        if ( $background_value > 24 ) {
                $return = 'RGB:0/0/0' ;
        } else {
                $return = 'RGB:f/f/f' ;
        }
        return $return ;
}


exit 0 ; }
