#!/usr/bin/perl

use strict;
use warnings;
use FileHandle;
use Getopt::Long;

Getopt::Long::Configure ("bundling", "gnu_compat");
STDOUT->autoflush;

my %options = (
		delimiter	=> "",
		count 		=> 0,
		help		=> 0,
		version		=> 0
	);
my $version = 0.1;
GetOptions ("delimiter|d=s" => \$options{'delimiter'}, "help|h" => \$options{'help'},
		 "count|c:i" => \$options{'count'}, "version|v" => \$options{'version'}
	 );
if ($options{'help'} == 1){
	print	"chop - removes characters from the end of a string\n" . 
		"Usage:\n" . 
		"   chop without paramters removes the last character from a given string, ignoring \\n\n" .
		"   -c, -- count N \t removes N characters from the end of a string\n" .
		"   -d, --delimiter X \t cuts of the end of a string until X is reached\n" .
		"Example:\n" .
	       	"\tuser\@host ~ \$ echo foo:bar:foo | chop -d \":\"	\n" .
		"\twill return \'foo:bar\'\n"   ;
		exit 0;
	}

if ($options{'version'} == 1){
	print "chop  - version $version\nAuthor: Haui, contact haui45\@web.de\n";
	exit 0;
}




foreach my $line (<STDIN>){
	if ($options{'delimiter'} ne ""){
		my $delimiter = $options{'delimiter'};
		my @array = split(/$delimiter/, $line);
		my $length = @array;
		if ($length == 1){
			print $line;
			next;
		}
		my $last = chomp ($array[$#array]);
		pop @array;
		if ($last == 1){
			print join $delimiter, @array;
			print "\n";
			next;
		}
		print join "", @array;
		next;
	}
	my $count = $options{'count'};
	if ($count == 0){
		my $last = chomp $line;
		chop $line;
		if ($last == 1){
			print $line . "\n";
		}
		else{
			print $line;
		}
		next;
	}
	else{
		my $last = chomp $line;
		if ($count >= length($line)){
			if ($last == 1){
				print "\n";
				next;
			}
			print "";
			next;
		}
		$line =~ s/.{$count}$//;
		if ($last == 1){
			print $line . "\n";
		}
		else{
			print $line;
		}
		next;

	}

}
