#!/usr/bin/perl

$progname = $0;
$progname =~ s~.*/~~;

if ($#ARGV != 1 && $#ARGV != 3) {
    die <<"EOT";

Usage: $progname  config_file  difference_table_file  [number_of_clusters  location_label]  >  map.ps

EOT
}

sub cleanup
{
    while (<$tmp*>) {
        unlink $_;
    }
}

sub mapccc
{
    my ($f) = $_[0];

    system('cluster', '-wa', '-c', '-N', .5, '-r', 50, '-o', "${tmp}_1", $f);
    system('cluster', '-ga', '-c', '-N', .5, '-r', 50, '-o', "${tmp}_2", $f);
    system('difsum', '-a', '-o', $tmp, "${tmp}_1", "${tmp}_2");
    system('mds', '-o', "$tmp.vec", 3, $tmp);
    system('maprgb', '-e', $ARGV[0], "$tmp.vec");
}

$tmp = "/tmp/mapccc_$$";

$SIG{ALRM} =
$SIG{INT} =
$SIG{QUIT} =
$SIG{TERM} =
$SIG{PIPE} =
    sub {
        cleanup;
        exit 1;
    };

if ($#ARGV == 1) {
    mapccc($ARGV[1]);
    cleanup;
    exit;
}


$groups = int($ARGV[2]);
$label = $ARGV[3];

if ($groups < 2) {
    die <<"EOT";

Error $progname: Illegal number of groups ($groups)

EOT
}

open(IN, "cluster -wm $ARGV[1] | clgroup -i -n $groups|");
while (<IN>) {
    if (/^\s*(\d+)\s+\"?(.*?)\"?\s*$/) {  ### FIX THIS ###
	push @grp, "$1\t$2";
	if ($2 eq $label) {
	    $index = $1;
	}
    }
}
close IN;

if (! $index) {
    die <<"EOT";

Error $progname: label "$label" not found in file $ARGV[1]

EOT
}

open(OUT, ">${tmp}_1");
foreach $g (@grp) {
    ($i, $j) = split /\t/, $g;
    if ($i == $index) {
	printf OUT ": $j\n- $j\n";
    }
}
close OUT;
system('difmod', '-o', "${tmp}.dif", $ARGV[1], "${tmp}_1");
mapccc("${tmp}.dif");
cleanup;
