#!/usr/local/bin/perl
#
# This CGI script presents the user with a form that can be used
# to try out the various options available with the SFU WWW
# access counter. Information on the counter program can be found
# at:
#  http://www.semcor.com/~muquit/Count.html
#
# This script was written by Ray Davison (ray@sfu.ca) and all comments
# should be directed my way.
#
# This CGI script uses a perl package that makes it easy to create
# Web fill-out forms. The current version of CGI.pm is available at:
#  http://www-genome.wi.mit.edu/ftp/pub/software/WWW/cgi_docs.html
#  ftp://ftp-genome.wi.mit.edu/pub/software/WWW/
#
BEGIN {
	unshift(@INC,'/home/ray/lib');
}
use CGI;

######################################################################
# Default values
######################################################################
$count_location = "http://www.sfu.ca/cgi-bin/count.cgi";
# display
$default_display_value = "counter";
# frame
$default_frame_thickness = 6;
$default_frame_red = 100;
$default_frame_green = 139;
$default_frame_blue = 216;
#transparency
$default_transparency_red = 0;
$default_transparency_green = 0;
$default_transparency_blue = 0;
#color change
$default_source_red = 0;
$default_source_green = 255;
$default_source_blue = 0;
$default_pen_red = 0;
$default_pen_green = 255;
$default_pen_blue = 255;
#rotate
$default_degrees_value = 270;
#counter
$default_maximum_digits = 6;
#clock/date
$default_time_format = 12;
$default_date_format = "MMDDYY";
$default_time_zone = "-0700";
#fonts
$default_fontgroup_value = "standard";
$default_font_value = "A";
$font_directory = "/usr/localzone/nshome/cgi-bin/Counter/digits";
#images
@available_images = ("/usr/local/www/docs/sfu-small-aerial.gif",
			"/usr/local/www/docs/redarrow.gif");
$default_image_value = $available_images[0];
%image_labels = ($available_images[0]=>"SFU picture",
		$available_images[1]=>"Small red arrow");
#pages
@available_pages = ("www.sfu.ca/ray/counter/demo.cgi",
                    "www.sfu.ca/ray/counter/index.html");
$default_page = $available_pages[0];
%page_labels = ($available_pages[0]=>"demo.cgi (this page)",
                $available_pages[1]=>"index.html");

######################################################################
# Initialize our CGI object
######################################################################

$query = new CGI;
$query->autoEscape(undef);

######################################################################
# Create the HTML header for the form
######################################################################
print $query->header();
print $query->start_html(-title=>'WWW Page Counter');
srand();

$myself = $query->self_url;
$tryme = $query->submit(-name=>"sub".int(rand(1000000)),-value=>'Try this out');

$unique = int(rand(1000000));
$hasreset = $query->param('hasreset');
#
# Start a form
#

print $query->startform;

#
# An explanation of what this is
#

print <<EOF;
<h1>SFU WWW Page Counter Demo Page</h1>
<p>Use this form to try out WWW page counters. 
To put a counter in your WEB page, copy the following command into
your document where you want the counter. Note that you must change
the <code><b>df=</b></code> option to contain the location of
your page.

<p>For an explanation of the various options, see the
<A HREF="http://www.sfu.ca/ray/counter/Docs/count.html">
Counter Documentation</A> page.
EOF

$referer = $ENV{'HTTP_REFERER'};
if ($referer =~ /^\s*$/) {
print <<EOF;
<p><b>Important Note:</b>The page counter won't work unless your
browser sends information identifying the page to be counted.
If the counter displays a sequence of 888888, it is because
your browser does not supply the needed information.
EOF
}

#
# Put together the <img src=...> command
#

$imgstring = "img src=\"" . $count_location . "?";

#
# Add the display item
#

# Initialize display values

$display = $query->param('display');
if ($display eq "") {$display = $default_display_value;}

# Add display items to the image string

if ($display ne $default_display_value && $display ne "image") {
  $imgstring .= "display=" . $display . "|";
}

#
# Add the Counter display items
#

# Initialize counter display items

if ($display eq "counter") {
  $md = $query->param('md');
  if ($md eq "") {
	$md = $default_maximum_digits;
  }
  $counter = $query->param('counter');

  # Add counter display items to image string

  $comma = $query->param('comma');
  if ($comma) {
	$imgstring .= "comma=T|";
  }
  if ($md != $default_maximum_digits) {
    $imgstring .= "md=" . $md . "|";
  }
  if ($counter eq 'random') {
    $imgstring .= "df=random|";
  } elsif ($counter eq 'literal') {
    $lit = $query->param('lit');
    $imgstring .= "lit=" . $lit . "|";
  } else {
    if ($counter eq 'hitcounter') {
      $pad = $query->param('pad');
      if (!$pad) {
        $imgstring .= "pad=F|";
      }
      $sh = $query->param('sh');
      if (!$sh) {
        $imgstring .= "sh=F|";
      }
      $incr = $query->param('incr');
      if (!$incr) {
        $imgstring .= "incr=F|";
      }
      $st = $query->param('st');
      if ($st ne "") {
        $imgstring .= "st=" . $st . "|";
        # check to see if the user is resetting our page counter
        $df = $query->param('df');
        if ($df eq "") {$df = $default_page;}
        if ($df eq $default_page) {
          $hasreset = 1;
        }
      }
    } else {
      $counter = 'hitcounter';
    }
  }
}

if ($hasreset) {
  print $query->hidden(-name=>'hasreset', -default=>1);
}

#
# Add clock items
#

# Initialize clock items
if ($display eq 'clock') {
  $tformat = $query->param('tformat');
  if ($tformat eq "") {$tformat = $default_time_format;}
  if ($tformat ne $default_time_format) {
  	$imgstring .= "tformat=" . $tformat . "|";
  }
  if ($query->param('tz')) {
    $timezone = $query->param('timezone');
    if ($timezone eq "") {$timezone = $default_time_zone;}
    $imgstring .= "timezone=GMT" . $timezone . "|";
  }
}

#
# Add date items
#

# Initialize date items

if ($display eq 'date') {
  $dformat = $query->param('dformat');
  if ($dformat eq "") {$dformat = $default_date_format;}
  if ($dformat ne $default_date_format) {
        $imgstring .= "dformat=" . $dformat . "|";
  }
  if ($query->param('dtz')) {
    $timezone = $query->param('dtimezone');
    if ($timezone eq "") {$timezone = $default_time_zone;}
    $imgstring .= "timezone=GMT" . $timezone . "|";
  }
}

#
# Add image items
#

# Initialize image items

if ($display eq 'image') {
	$image = $query->param('image');
	if ($image eq "") {$image = $default_image_value;}
	$imgstring .= "image=" . $image . "|";
}

#
# Add the frame items
#

# Initialize frame values

$ft = $query->param('ft');
if ($ft eq "") {$ft = $default_frame_thickness;}
$fcolor = $query->param('fcolor');
if ($fcolor eq "") {
  $fcolor = 'RGB';
  $f_red = $default_frame_red;
  $f_green = $default_frame_green;  
  $f_blue = $default_frame_blue;
} elsif ($fcolor eq 'RGB') {
  $f_red = $query->param('f_red');
  $f_green = $query->param('f_green');
  $f_blue = $query->param('f_blue');
} elsif ($fcolor eq 'Hex') {
  $f_hex = $query->param('f_hex');
} elsif ($fcolor eq 'Name') {
  $f_name = $query->param('f_name');
}
if ($fcolor eq 'RGB') {
  $f_hex = rgb2hex($f_red, $f_green, $f_blue);
  $f_name = rgb2name($f_red, $f_green, $f_blue);
} elsif ($fcolor eq 'Hex') {
  ($f_red,$f_green,$f_blue) = hex2rgb($f_hex);
  $f_name = rgb2name($f_red, $f_green, $f_blue);
} elsif ($fcolor eq 'Name') {
  ($f_red,$f_green,$f_blue) = name2rgb($f_name);
  $f_hex = rgb2hex($f_red, $f_green, $f_blue);
}

# Add frame items to the image string

if ($ft == 0) {
  $imgstring .= "ft=0|";
} else {
  if ($ft != $default_frame_thickness) {
    $imgstring .= "ft=" . $ft . "|";
  }
  if ($f_red!=$default_frame_red || $f_green!=$default_frame_green || $f_blue!=$default_frame_blue) {
    if ($fcolor eq 'RGB') {
      $imgstring .= "frgb=".$f_red.";".$f_green.";".$f_blue."|";
    } elsif ($fcolor eq 'Hex') {
      $imgstring .= "frgb=".$f_hex."|";
    } else {
      $imgstring .= "frgb=".$f_name."|";
    }
  }
}

#
# Add transparency items
#

# Initialize transparency values

$tr = $query->param('tr');
$trcolor = $query->param('trcolor');
if ($trcolor eq "") {
  $trcolor = 'RGB';
  $tr_red = $default_transparency_red;
  $tr_green = $default_transparency_green;
  $tr_blue = $default_transparency_blue;
} elsif ($trcolor eq 'RGB') {
  $tr_red = $query->param('tr_red');
  $tr_green = $query->param('tr_green');
  $tr_blue = $query->param('tr_blue');
} elsif ($trcolor eq 'Hex') {
  $tr_hex = $query->param('tr_hex');
} elsif ($trcolor eq 'Name') {
  $tr_name = $query->param('tr_name');
}
if ($trcolor eq 'RGB') {
  $tr_hex = rgb2hex($tr_red, $tr_green, $tr_blue);
  $tr_name = rgb2name($tr_red, $tr_green, $tr_blue);
} elsif ($trcolor eq 'Hex') {
  ($tr_red,$tr_green,$tr_blue) = hex2rgb($tr_hex);
  $tr_name = rgb2name($tr_red, $tr_green, $tr_blue);
} elsif ($trcolor eq 'Name') {
  ($tr_red,$tr_green,$tr_blue) = name2rgb($tr_name);
  $tr_hex = rgb2hex($tr_red, $tr_green, $tr_blue);
}

# Add transparency items to the image string

if ($tr) {
  if ($tr_red!=$default_transparency_red || 
      $tr_green!=$default_transparency_green || 
      $tr_blue!=$default_transparency_blue) {
    if ($trcolor eq 'RGB') {
      $imgstring .= "trgb=".$tr_red.";".$tr_green.";".$tr_blue."|";
    } elsif ($trcolor eq 'Hex') {
      $imgstring .= "trgb=".$tr_hex."|";
    } else {
      $imgstring .= "trgb=".$tr_name."|";
    }
  } else {
    $imgstring .= "tr=T|";
  }
}

#
# Add color change items
#

# Initialize color change values

$negate = $query->param('negate');
$chcolor = $query->param('chcolor');
$scolor = $query->param('scolor');
if ($scolor eq "") {
  $scolor = 'RGB';
  $s_red = $default_source_red;
  $s_green = $default_source_green;
  $s_blue = $default_source_blue;
} elsif ($scolor eq 'RGB') {
  $s_red = $query->param('s_red');
  $s_green = $query->param('s_green');
  $s_blue = $query->param('s_blue');
} elsif ($scolor eq 'Hex') {
  $s_hex = $query->param('s_hex');
} elsif ($scolor eq 'Name') {
  $s_name = $query->param('s_name');
}
if ($scolor eq 'RGB') {
  $s_hex = rgb2hex($s_red, $s_green, $s_blue);
  $s_name = rgb2name($s_red, $s_green, $s_blue);
} elsif ($scolor eq 'Hex') {
  ($s_red,$s_green,$s_blue) = hex2rgb($s_hex);
  $s_name = rgb2name($s_red, $s_green, $s_blue);
} elsif ($scolor eq 'Name') {
  ($s_red,$s_green,$s_blue) = name2rgb($s_name);
  $s_hex = rgb2hex($s_red, $s_green, $s_blue);
}

$pcolor = $query->param('pcolor');
if ($pcolor eq "") {
  $pcolor = 'RGB';
  $p_red = $default_pen_red;
  $p_green = $default_pen_green;
  $p_blue = $default_pen_blue;
} elsif ($pcolor eq 'RGB') {
  $p_red = $query->param('p_red');
  $p_green = $query->param('p_green');
  $p_blue = $query->param('p_blue');
} elsif ($pcolor eq 'Hex') {
  $p_hex = $query->param('p_hex');
} elsif ($pcolor eq 'Name') {
  $p_name = $query->param('p_name');
}
if ($pcolor eq 'RGB') {
  $p_hex = rgb2hex($p_red, $p_green, $p_blue);
  $p_name = rgb2name($p_red, $p_green, $p_blue);
} elsif ($pcolor eq 'Hex') {
  ($p_red,$p_green,$p_blue) = hex2rgb($p_hex);
  $p_name = rgb2name($p_red, $p_green, $p_blue);
} elsif ($pcolor eq 'Name') {
  ($p_red,$p_green,$p_blue) = name2rgb($p_name);
  $p_hex = rgb2hex($p_red, $p_green, $p_blue);
}

# Add color change items to the image string

if ($chcolor) {
  if ($s_red!=$default_source_red || 
      $s_green!=$default_source_green || 
      $s_blue!=$default_source_blue ||
      $p_red!=$default_pen_red || 
      $p_green!=$default_pen_green || 
      $p_blue!=$default_pen_blue) {
    if ($scolor eq 'RGB') {
      $imgstring .= "srgb=".$s_red.";".$s_green.";".$s_blue."|";
    } elsif ($scolor eq 'Hex') {
      $imgstring .= "srgb=".$s_hex."|";
    } else {
      $imgstring .= "srgb=".$s_name."|";
    }
    if ($pcolor eq 'RGB') {
      $imgstring .= "prgb=".$p_red.";".$p_green.";".$p_blue."|";
    } elsif ($pcolor eq 'Hex') {
      $imgstring .= "prgb=".$p_hex."|";
    } else {
      $imgstring .= "prgb=".$p_name."|";
    }
  } else {
    $imgstring .= "chcolor=T|";
  }
}
if ($negate) {
  $imgstring .= "negate=T|";
}

#
# Add the rotate item
#

# Initialize rotate values

$rotate = $query->param('rotate');
$degrees = $query->param('degrees');
if ($degrees eq "") {$degrees = $default_degrees_value;}

# Add display items to the image string

if ($rotate) {
  if ($degrees ne $default_degrees_value) {
    if ($degrees != 0) {
      $imgstring .= "degrees=" . $degrees . "|";
    }
  } else {
    $imgstring .= "rotate=T|";
  }
}

#
# Add the font item
#

# Initialize font values

$fontgroup = $query->param('fontgroup');
if ($fontgroup eq "") {
	$fontgroup = $default_fontgroup_value;
	$font = $default_font_value;
} else {
	$font = $query->param($fontgroup);
}
$dd = "";
if ($fontgroup ne $default_fontgroup_value) {
	$dd = $fontgroup . "/";
}
$dd .= $font;

# Add font items to the image string

if ($dd ne $default_font_value && $display ne "image") {
	$imgstring .= "dd=" . $dd . "|";
}

#
# Add the trailing quote and angle bracket
# 

$endstr = "";
$enddisp = "";
if ($counter eq 'hitcounter') {
  $df = $query->param('df');
  if ($df eq "") {$df = $default_page;}
  $endstr = "df=" . $df;
  #
  # insert a random number into the file name of the page to be 
  # counted. This insures that if we want to display a count using
  # the same options as we did earlier, the browser won't just grab
  # a copy out of its cache.
  #
  $enddisp = "df=" . $unique . "/" . $df;
  #
  # if the user has used the "reset the counter" option
  # then don't count our real page (we don't want its counter played with)
  #
  if ($hasreset && $df eq $default_page) {
    $enddisp .= "xxx";
  }
} else {
  if (substr($imgstring,-1,1) eq "|") 
    {chop($imgstring);}  # Delete final "|" if present
}

$endstr .= "\">";
$enddisp .= "\">";

print <<EOF;
<p>Use the command:
<p><nobr><code>&lt;$imgstring$endstr </code></nobr>
<p>To display:
<p><$imgstring$enddisp

<p>By changing the options that follow and clicking on a
$tryme button, you can vary the appearance of the
counter in a variety of ways. The changes you make to the options will
change the counter image above, and will change the HTML
command above so that you can copy it and paste it into your document.
EOF

#print "<p>\n";
#print $query->dump();
#print "<p>\n";

#
# Now display the various options the user can play with
#

#
# Some info on selecting different options
#

@displaytypes = $query->radio_group('display',
			['counter','clock','date','image'],'counter');

print <<EOF;
<hr>
<A NAME="select">
<h2>Getting Started</h2>
</A>
The counter program has a variety of options.
You can select the type of display you want from the
following list and then have a look at the options
that apply to that type of display, or at the options
that apply to any of the display types.
<TABLE>
<TR><TD><p>$displaytypes[0]<TD><A HREF=#counter_options>Counter Options</A>
<TD>Use this option to display a counter of some type.
<TR><TD><p>$displaytypes[1]<TD><A HREF=#clock_options>Clock Options</A>
<TD>Use this option to display the time.
<TR><TD><p>$displaytypes[2]<TD><A HREF=#date_options>Date Options</A>
<TD>Use this option to display the date.
<TR><TD><p>$displaytypes[3]<TD><A HREF=#image_options>Image Options</A>
<TD>Use this option to display a GIF image.
<TR><TD><TD valign=top><p><A HREF=#global_options>Style Options</A>
<TD>These are options that apply to any of the above display types.
These options include:
<br><A HREF=#frame_options>Adding a frame.</A>
<br><A HREF=#transparency_options>Adding transparency.</A>
<br><A HREF=#color_options>Changing a color.</A>
<br><A HREF=#rotate_options>Rotating the image.</A>
<br><A HREF=#font_options>Changing the digit style.</A>
</TABLE>
EOF

showsubmit();

#
# Display the Counter options
#
@countertypes = $query->radio_group('counter',
                        ['hitcounter','random','literal'],'hitcounter');
$literaldisplay = $query->textfield(-name=>'lit',-default=>'',
                        -size=>10,-maxlength=>15);
$startcount = $query->textfield(-name=>'st',-default=>'',
                        -size=>10,-maxlength=>10);
$zeropadding = $query->checkbox(-name=>'pad',-checked=>'checked',-label=>'');
$showdigits = $query->checkbox(-name=>'sh',-checked=>'checked',-label=>'');
$incrementcount = $query->checkbox(-name=>'incr',-checked=>'checked',-label=>'');
$datafile = $query->popup_menu(-name=>'df',
     -values=>\@available_pages,
     -default=>$default_page,
     -labels=>\%page_labels);
$displaycomma = $query->checkbox(-name=>'comma',-label=>'');
$maximumdigits = $query->popup_menu(-name=>'md',
                 -values=>['5','6','7','8','9','10'],
                 -default=>$default_maximum_digits);

print <<EOF;
<A NAME="counter_options"><h2>Counter Options</h2></A>

<p>The following options apply if you have 
<A HREF=#select>selected</A> to
display a counter (rather than a clock, date or GIF image).

<p>There are three kinds of counters.
For each of the counter types, there are a number of
options that apply to that type.

<p>The following options apply to all the following counter types:
<UL>
<li>To display commas every third digit, select this box: $displaycomma
</UL> 

Choose the type of counter from the list below.

<p>$countertypes[1]
  <blockquote>
  This will display a random number.
  </blockquote>
<p>$countertypes[2]
  <blockquote>
  This allowes you to specify what number you want displayed.
  Enter the value you want displayed here: $literaldisplay
  </blockquote>
<p>$countertypes[0]
  <blockquote>
  A hitcounter displays the number of times a WEB page has been viewed.
  The following options can be used to modify the appearance of the 
  counter.
  <UL>
  <li>To pad with leading zeros, select this box: $zeropadding
      (this defaults on.)
  <li>You can choose to show the counter on your page or have the
      counter invisible (but still have the count
      for the page incremented). To have the counter visible, select
      this box: $showdigits (the default is to show the counter.)
  <li>It is possible to display the count with or without incrementing 
      the count. This can be used to examine the count for reporting or
      other purposes without adding to the count. To have the counter
      incremented, select this box: $incrementcount (the default is
      to increment the counter.)
  <li>To restart the count at a new value, enter the count here: $startcount
      (this should not be left in or the counter will stay at the value you
      enter because it will be reset every time someone views your page.)
  <li>You can show the count for this page or another page in the same
      directory as this page. Select the page to count from this list:
      $datafile
      <br>Click <A href="index.html">here</A> to have a look at the other page.
  <li>Select the maximum number of digits to display from the following 
      pop-up menu: $maximumdigits
  </UL>
  </blockquote>

<p>For more options that apply to counters (as well as time,
clock and GIF displays) see <A HREF=#global_options>Style Options</A>.
<p>These options include:
<br><A HREF=#frame_options>Adding a frame.</A>
<br><A HREF=#transparency_options>Adding transparency.</A>
<br><A HREF=#color_options>Changing a color.</A>
<br><A HREF=#rotate_options>Rotating the image.</A>
<br><A HREF=#font_options>Changing the digit style.</A>

EOF

showsubmit();

#
# Display the Clock options
#

print <<EOF;
<A NAME="clock_options"><h2>Clock Options</h2></A>

<p>The following options apply if you have 
<A HREF=#select>selected</A> to
display a clock (rather than a counter, date or GIF image).

<p>There are two options for the clock display. You can choose
12 or 24 hour format, and you can select the timezone. The 
timezone must be specified with a negative or positive four digit
offset from GMT. For example, the time in B.C. would be represented
by -0700 (or -0800 for daylight saving time).
EOF

print "<p>",$query->popup_menu(-name=>'tformat',-values=>['12','24'],
           -default=>$default_time_format),"\n";
print "<b>hour format</b>\n";

print "<p><b>Use Timezone</b>",$query->checkbox(-name=>'tz',-label=>'');
print $query->textfield(-name=>'timezone',-default=>$default_time_zone,
                 -size=>5,-maxlen=>5);

showsubmit();

# 
# Display the Date options
#

print <<EOF;
<A NAME="date_options"><h2>Date Options</h2></A>

<p>The following options apply if you have 
<A HREF=#select>selected</A> to
display a date (rather than a counter, clock or GIF image).

<p>There are two options for the date display. You can choose what order
the day, month and year digits are displayed (choose from the pop-up menu),
and you can specify the timezone that you want the date displayed for.
See the discussion of timezone under Clock Options above for more information
on specifying a timezone.
EOF

print "<p><b>Date Format</b>",
          $query->popup_menu(-name=>'dformat',
              -values=>['MMDDYY','MMYYDD','DDMMYY','DDYYMM','YYDDMM','YYMMDD'],
              -default=>$default_date_format),"\n";

print "<p><b>Use Timezone</b>",$query->checkbox(-name=>'dtz',-label=>'');
print $query->textfield(-name=>'dtimezone',-default=>$default_time_zone,
                 -size=>5,-maxlen=>5);

showsubmit();

#
# Display the Image options
#

print <<EOF;
<A NAME="image_options"><h2>Image Options</h2></A>

<p>The following options apply if you have 
<A HREF=#select>selected</A> to
display an image (rather than a counter, clock or date).
You can use the page counter to display an arbitrary GIF
image. This allows you to modify the image using the various
options (such as adding a border).
EOF

print "<p>Choose one of the following pictures: ";
print $query->popup_menu(-name=>'image', -values=>\@available_images,
		-default=>$default_image_value,
		-labels=>\%image_labels);
showsubmit();

#
# Diplay the Global Options
#

print <<EOF;
<A NAME="global_options"><h2>Global Options</h2></A>

<p>The following options apply to all display types
(counter, clock, date or image).

<p>The following options are available:
<TABLE>
<TR><TD><p><A HREF=#frame_options>Click Here</A>
<TD>for Frame options.
<TR><TD><p><A HREF=#transparency_options>Click Here</A>
<TD>for Transparency options.
<TR><TD><p><A HREF=#color_options>Click Here</A>
<TD>for options to change colors.
<TR><TD><p><A HREF=#rotate_options>Click Here</A>
<TD>for options to rotate the image.
<TR><TD><p><A HREF=#font_options>Click Here</A>
<TD>for options to select the font.
</TABLE>
<hr>
EOF

#
# Display the Frame Options
#

$ftbox = $query->textfield(-name=>'ft',-default=>'6',-size=>5,-maxlength=>10);
@fcselect = $query->radio_group(-name=>'fcolor',
		-values=>['RGB','Hex','Name'],
		-default=>'RGB');
$redbox = $query->textfield(-name=>'f_red',-default=>$f_red,-force=>1,
		-size=>3,-maxlen=>3);
$greenbox = $query->textfield(-name=>'f_green',-default=>$f_green,-force=>1,
		-size=>3,-maxlen=>3);
$bluebox = $query->textfield(-name=>'f_blue',-default=>$f_blue,-force=>1,
		-size=>3,-maxlen=>3);
$hexbox = $query->textfield(-name=>'f_hex',-default=>$f_hex,-force=>1,
		-size=>6,-maxlen=>6);
$namebox = $query->textfield(-name=>'f_name',-default=>$f_name,-force=>1,
		-size=>15,-maxlen=>20);

print <<EOF;
<A NAME="frame_options"><h2>Frame Options</h2></A>

<p>You can wrap the counter in an ornamental frame.
You can specify the thickness of the frame (use zero for no frame)
as well as the color. You can specify the color with three RGB values
between 0 and 255, a Netscape like hex string or a color name.

<TABLE>
<TR><TD><p><b>Frame<br>Thickness</b>
    <TD>$ftbox<TD><p><b>Frame<br>Color</b>
    <TD><font size=7>{</font>
    <TD><TABLE>
        <TR><TD><p>$fcselect[0] <TD>$redbox $greenbox $bluebox
        <TR><TD><p>$fcselect[1] <TD>$hexbox
        <TR><TD><p>$fcselect[2] <TD>$namebox
        </TABLE>
</TABLE>
EOF

showsubmit();

#
# Display the transparency information
#

$trbox = $query->checkbox(-name=>'tr',-label=>'');
@trselect = $query->radio_group(-name=>'trcolor',
                                -value=>['RGB','Hex','Name'],
                                -default=>'RGB');
$redbox = $query->textfield(-name=>'tr_red',-default=>$tr_red,-force=>1,
                            -size=>3,-maxlen=>3);
$greenbox = $query->textfield(-name=>'tr_green',-default=>$tr_green,-force=>1,
                            -size=>3,-maxlen=>3);
$bluebox = $query->textfield(-name=>'tr_blue',-default=>$tr_blue,-force=>1,
                            -size=>3,-maxlen=>3);
$hexbox = $query->textfield(-name=>'tr_hex',-default=>$tr_hex,-force=>1,
                            -size=>6,-maxlen=>6);
$namebox = $query->textfield(-name=>'tr_name',-default=>$tr_name,-force=>1,
                            -size=>15,-maxlen=>20);

print <<EOF;
<A NAME="transparency_options"><h2>Transparency Options</h2></A>

<p>You can specify that your counter image will have a transparent color.
You must specify explicitly which color to make transparent.

<TABLE>
<TR><TD><p><b>Transparency<br>On</b>
    <TD>$trbox<TD><p><b>Transparent<br>Color</b>
    <TD><font size=7>{</font>
    <TD><TABLE>
        <TR><TD><p>$trselect[0] <TD>$redbox $greenbox $bluebox
        <TR><TD><p>$trselect[1] <TD>$hexbox
        <TR><TD><p>$trselect[2] <TD>$namebox
        </TABLE>
</TABLE>
EOF

showsubmit();

#
# Display the color change information
#

$ccbox = $query->checkbox(-name=>'chcolor',-label=>'');
@cfselect = $query->radio_group(-name=>'scolor',
                                -value=>['RGB','Hex','Name'],
                                -default=>'RGB');
$fredbox = $query->textfield(-name=>'s_red',-default=>$s_red,-force=>1,
                            -size=>3,-maxlen=>3);
$fgreenbox = $query->textfield(-name=>'s_green',-default=>$s_green,-force=>1,
                            -size=>3,-maxlen=>3);
$fbluebox = $query->textfield(-name=>'s_blue',-default=>$s_blue,-force=>1,
                            -size=>3,-maxlen=>3);
$fhexbox = $query->textfield(-name=>'s_hex',-default=>$s_hex,-force=>1,
                            -size=>6,-maxlen=>6);
$fnamebox = $query->textfield(-name=>'s_name',-default=>$s_name,-force=>1,
                            -size=>15,-maxlen=>20);
@ctselect = $query->radio_group(-name=>'pcolor',
                                -value=>['RGB','Hex','Name'],
                                -default=>'RGB');
$tredbox = $query->textfield(-name=>'p_red',-default=>$p_red,-force=>1,
                            -size=>3,-maxlen=>3);
$tgreenbox = $query->textfield(-name=>'p_green',-default=>$p_green,-force=>1,
                            -size=>3,-maxlen=>3);
$tbluebox = $query->textfield(-name=>'p_blue',-default=>$p_blue,-force=>1,
                            -size=>3,-maxlen=>3);
$thexbox = $query->textfield(-name=>'p_hex',-default=>$p_hex,-force=>1,
                            -size=>6,-maxlen=>6);
$tnamebox = $query->textfield(-name=>'p_name',-default=>$p_name,-force=>1,
                            -size=>15,-maxlen=>20);
$neg = $query->checkbox(-name=>'negate',-label=>'');
print <<EOF;
<A NAME="color_options"><h2>Color Options</h2></A>

<p>Any one color of the image can be changed to a different color on the fly.
You can also negate the color of the counter digits.
Note that the Frame is exempted from negation.

<TABLE>
<TR><TD><p><b>Change<br>Color</b>
    <TD>$ccbox<TD><p><b>From<br>This<br>Color</b>
    <TD><font size=7>{</font>
    <TD><TABLE>
        <TR><TD><p>$cfselect[0] <TD>$fredbox $fgreenbox $fbluebox
        <TR><TD><p>$cfselect[1] <TD>$fhexbox
        <TR><TD><p>$cfselect[2] <TD>$fnamebox
        </TABLE>
    <TD><p><b>To<br>This<br>Color</b>
    <TD><font size=7>{</font>
    <TD><TABLE>
        <TR><TD><p>$ctselect[0] <TD>$tredbox $tgreenbox $tbluebox
        <TR><TD><p>$ctselect[1] <TD>$thexbox
        <TR><TD><p>$ctselect[2] <TD>$tnamebox
        </TABLE>
</TABLE>

<p><b>Negate Color</b> $neg
EOF

showsubmit();

#
# Display the rotate information
#

%labels = ('90'=>'90 degrees','180'=>'180 degrees','270'=>'270 degrees');
$rotbox = $query->checkbox(-name=>'rotate',-label=>'');
$rotvalue = $query->popup_menu(-name=>'degrees',
                         -values=>['90','180','270'],
                         -default=>$default_degrees_value,
                        -labels=>\%labels);
print <<EOF;
<A NAME="rotate_options"><h2>Rotate Options</h2></A>

<p>You can rotate the counter image.

<TABLE>
<TR><TD><p><b>Rotate<br>Image</b>
    <TD>$rotbox <TD>$rotvalue
</TABLE>
EOF

showsubmit();

#
# Display the available fonts
#

opendir(DIR,$font_directory);
local(@standardfonts) = grep(/^[ABCDE]$/,readdir(DIR));
closedir(DIR);

#
# Use the GIF comment information to find out which characters
# are available for this font. Include this information in the pop-up
# menu. A GIF comment starts with x21 xFE and a one byte length.
# The strip.gif images used by the counter contain the number of images
# in the comment. This number will range from 10 to 15 (all images
# contain at least the characters 0123456789).
#
local(%standardlabels) = ();
foreach $font (@standardfonts) {
  $extrainfo = " (0123456789";
  open(DIGDATA, $font_directory."/".$font."/strip.gif");
  $digdata = "";
  while (<DIGDATA>) {
    $digdata .= $_;
  }
  if ($digdata =~ m/\x21\xfe.(\d\d):/) {
   if ($1 > 10) {$extrainfo .= ":";}
   if ($1 > 11) {$extrainfo .= "a";}
   if ($1 > 12) {$extrainfo .= "p";}
   if ($1 > 13) {$extrainfo .= ",";}
   if ($1 > 14) {$extrainfo .= "-";}
  }
  $extrainfo .= ")";
  close(DIGDATA);
  $standardlabels{$font} = $font . $extrainfo;
}

opendir(DIR,$font_directory);
local(@fontclasses) = sort(grep(/^[^\.].+$/,readdir(DIR)));
closedir(DIR);

print <<EOF;
<A NAME="font_options"><h2>Font Options</h2></A>

<p>You can choose different fonts (character sets) to
be used for the counter. Note that not all the fonts have
all the characters you need for all the displays. The following
characters are needed:
<UL>
  <LI>The digits 0 to 9.
  <LI>The comma if you have chosen to display commas.
  <LI>The colon and some way to display AM and PM if you have 
chosen to display a clock.
  <LI>A dash if you have chosen to display the date.
</UL>
All the fonts in the <b>standard</b> collection contain all the 
characters above. Most of the other fonts only contain the digits.
Some contain the clock characters, and a very few contain the dash.

<p>Each font name is followed by a
parenthesised list of the characters it contains. You can use this
information to tell if you can use the font for a clock or date display.

<p>Choose the font for the counter as follows.
First choose a font family using the choices to the left,
then a font from that family from the popup list next to
the font family you chose.
EOF

print "<TABLE>\n";
print "<TR><TD><p>";
print $query->radio_group(-name=>'fontgroup',
			-values=>[$default_fontgroup_value],
			-default=>$default_fontgroup_value);
print "<TD>";
print $query->popup_menu(-name=>$default_fontgroup_value,
			-values=>\@standardfonts,
			-default=>$default_font_value,
                        -labels=>\%standardlabels),"\n";
for (@fontclasses) {
        $nextfont = $_;
	print "<TR><TD><p>";
	print $query->radio_group(-name=>'fontgroup',-values=>[$nextfont],
		-default=>$default_fontgroup_value);
	print "<TD>";
	opendir(DIR,$font_directory."/".$nextfont);
	local(@myfonts) = sort(grep(!/^\.\.?$/,readdir(DIR)));
	closedir(DIR);
local(%mylabels) = ();
foreach $font (@myfonts) {
  $extrainfo = " (0123456789";
  open(DIGDATA, $font_directory."/".$nextfont."/".$font."/strip.gif");
  $digdata = "";
  while (<DIGDATA>) {
    $digdata .= $_;
  }
  if ($digdata =~ m/\x21\xfe.(\d\d):/) {
   if ($1 > 10) {$extrainfo .= ":";}
   if ($1 > 11) {$extrainfo .= "a";}
   if ($1 > 12) {$extrainfo .= "p";}
   if ($1 > 13) {$extrainfo .= ",";}
   if ($1 > 14) {$extrainfo .= "-";}
  }
  $extrainfo .= ")";
  close(DIGDATA);
  $mylabels{$font} = $font . $extrainfo;
}

	print $query->popup_menu(-name=>$nextfont,-values=>\@myfonts,
                                 -labels=>\%mylabels),"\n";
}
print "</TABLE>\n";

showsubmit();

#
# Finish off the form
#

print <<EOF;
<hr>
<P>
<FONT SIZE="-1">
This counter demo form was developed and is maintained by 
<A HREF="mailto:ray\@sfu.ca">Ray Davison</A>.
Please send any comments my way.
<p>The counter program itself was developed by 
<A HREF="mailto:ma_muquit\@fccc.edu">Muhammad A Muquit</A>.
However, please don't bother him with questions as his program
was modified before being installed at SFU. His original documentation
for the program can be found 
<A HREF="http://www.fccc.edu/users/muquit/Count.html">here</A>.
<p>If you would like to see the source for this demo page
you can click 
<A HREF="http://www.sfu.ca/ray/counter/listing.cgi">here</A>.
EOF

print $query->endform;
print $query->end_html;

######################################################################
# Subroutines
######################################################################

sub rgb2hex {
	local($red,$green,$blue) = @_;
	if ($red < 0) {$red = 0;}
	if ($green < 0) {$green = 0;}
	if ($blue < 0) {$blue = 0;}
	if ($red > 255) {$red = 255;}
	if ($green > 255) {$green = 255;}
	if ($blue > 255) {$blue = 255;}
	sprintf("%2.2lx",$red) . sprintf("%2.2lx",$green) . sprintf("%2.2lx",$blue);
}
sub hex2rgb {
	local($hex) = @_;
	while (length($hex)<6) {substr($hex,0,0)="0";}
	s/[^0-9a-fA-F]/0/g;
	(hex(substr($hex,0,2)),hex(substr($hex,2,2)),hex(substr($hex,4)));
}
sub rgb2name {
	local($red,$green,$blue) = @_;
	local($NextLine);
    local($name) = "";
    
    open(COLORMAP, '/usr/localzone/nshome/cgi-bin/Counter/rgb.txt');
    while ($NextLine = <COLORMAP>) {
      if ($NextLine=~/^\s*($red)\s+($green)\s+($blue)\s+([^\n\s]*)\n$/) {
      	$name=$4;
		last;
      }
    }
    close(COLORMAP);
    $name;
}
sub name2rgb {
	local($name) = @_;
	local($red) = "";
	local($green) = "";
	local($blue) = "";
	local($NextLine);
	
	$name =~ tr/A-Z/a-z/;
    open(COLORMAP, '/usr/localzone/nshome/cgi-bin/Counter/rgb.txt');
    while ($NextLine = <COLORMAP>) {
      $NextLine =~ tr/A-Z/a-z/;
      if ($NextLine=~/^\s*(\d+)\s+(\d+)\s+(\d+)\s+($name)\s*$/) {
        $red = $1;
        $green = $2;
        $blue = $3;
        last;
      }
    }
	close(COLORMAP);
	($red,$green,$blue);
}
sub showsubmit {
print <<EOF;
<TABLE WIDTH=100%>
<TR><TD><hr width=200 ALIGN=LEFT><TD>$tryme
</TABLE>
EOF
}