#!/usr/bin/perl
#
# qccat is (c)2000 Brian Connors under terms of the Mozilla Public
# License.
#
# This is the 092400 version. 

use Getopt::Std;

# parse command line options first

getopts("adhprstv?",\%option);

# In case someone doesn't know what qccat does...

$usage ="usage: qccat -adhprstv \n
See \"man qccat\" for further details.\n";

$about = "qccat v1.0, 24 Sept 2000.\n
A parser for CueCat barcode scanners.\n
(c)2000 Brian Connors under terms of the Mozilla Public License.\n";
	
$seq = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';


sub decode
{
    ($encoded) = @_;
    @s = map { index($seq,$_); } split(//,$encoded);
    $l = ($#s+1) % 4;
    if ($l)
    {
	if ($l == 1)
	{
	    print "Error!";
	    return;
	}
	$l = 4-$l;
	$#s += $l;
    }
    $r = '';
    while ($#s >= 0)
    {
	$n = (($s[0] << 6 | $s[1]) << 6 | $s[2]) << 6 | $s[3];
	$r .=chr(($n >> 16) ^ 67) .
	     chr(($n >> 8 & 255) ^ 67) .
	     chr(($n & 255) ^ 67);
	@s = @s[4..$#s];
    }
    $r = substr($r,0,length($r)-$l);
    return $r;
}

# just looking around -- print help and disappear

if ($option{'?'}) {
	print $usage;
	exit(0);

# display about box

} elsif ($option{a}) {
	print $about;

#or if you need a prompt

} elsif ($option{p}) {
	print "Scan a barcode now: ";
}

# Read precisely one scan via keyboard wedge and parse it.

$s = <STDIN>;
chomp($s);
@fields = split(/\./,$s);
@results = map(decode($_), @fields[1..$#fields]);

if ($option{d}) { 	# suppresses serial number display
	@results[0] = "";
}

if ($option{h}) {	# Prints out in the style of cat.pl
	unless($option{d}) {
		print "CCSN: ",@results[0], "\n";
	}
	print "type: ",@results[1],"\n";
	print "value: ",@results[2],"\n";
} elsif ($option{r}) {	# Echo raw input. Not too useful.
	print $s;
} elsif ($option{s}) { 	# serial number only
	print @results[0];
} elsif ($option{t}) {	# bar code type only
	print @results[1];
} elsif ($option{v}) {	# value only
	print @results[2];
} else {
	print join("::",@results);
}


