#!/usr/bin/perl

# Copyright (C) 2010 Thorsten Kukuk
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# in Version 2 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA  02110-1301, USA.

=head1 NAME

    quersumme - calculate checksum of a number

=head1 SYNOPSIS

    quersumme [options] [number ...]

=head1 DESCRIPTION

    Calculates the checksum (or one-digit-checksum) of a number.

=head1 OPTIONS

    -1|--single         Calculate one digit checksum.
    -s|--search sum     Search a number with checksum "sum"
    --rangelow number   Start search with "number" (default 0)
    --rangehigh number  Search until number "number". If not specified,
                        search will aborted with first match.
    --version           Print version number and exit
    --usage             Print usage
    -h|-?|--help	Help

=cut

use strict;
use warnings;
use Pod::Usage;

#
# process command line arguments
#
use Getopt::Long;
my $single = 0;
my $help = 0;
my $man = 0;
my $version = 0;
my $usage = 0;
my $search = 0;
my $rangelow = 0;
my $rangehigh;

GetOptions('1|single' => \$single,
	   's|search=s' => \$search,
	   'rangelow=s' => \$rangelow,
	   'rangehigh=s' => \$rangehigh,
	   'version' => \$version,
	   'man' => \$man,
	   'u|usage' => \$usage,
	   'help|h|?' => \$help) or pod2usage(2);
pod2usage(0) if $help;
pod2usage(-exitstatus => 0, -verbose => 2) if $man;
pod2usage(-exitstatus => 0, -verbose => 0) if $usage;

if ($version) {
  print "quersumme (geo-tools) 1.23\n";
  exit;
}

if ($search) {
  if ($rangehigh) {
    for (my $i = $rangelow; $i <= $rangehigh; $i++) {
      print "$i\n" if (quersumme($i) == $search);
    }
  } else {
    my $i = $rangelow;
    while (quersumme($i) != $search) {
      $i++;
    }
    print "$i\n";
  }
} elsif ($#ARGV >= 0) {
  foreach (@ARGV) {
    my $number = $_;
    print quersumme($number), "\n";
  }
} elsif (($#ARGV < 0) ||($#ARGV == 0 && $ARGV[0] eq "-")) {
  # read from tty
  while (<>) {
    chomp;
    my $number = $_;
    print quersumme($number), "\n";
  }
}

exit;

sub quersumme {
  my @wert = split //,$_[0];
  my $sum = 0;

  foreach (@wert) {
    $sum += $_
  }

  if ($single && $sum > 9) {
    return quersumme ($sum);
  }

  return $sum;
}
