#!/usr/bin/perl
# 
# SubShifter v.0.1
# SubShift shifts timing of .sub-files
#
# Copyright (c) 2005 Joni Valtanen
# GNU General Public Licence v2
#
# How this works:
# -reads and parses command line arguments
# -reads given file line by line
# -parses start,stop and textfrom line
# -increases or decreases subtitle start and stop value with given value
# -prints new shifted subtitles to file or stdout
#
#
# Command line arguments:
# -t shifting time in milliseconds>
# -i inputfile 
# -o outputfile (optional)
# -d minus decrease
#
#
# Exit codes:
# 0 - out from help and version
# 1 - not enought arguments
# 2 - no inputfile
# 3 - time is not numeric value
#
#
# Version information
#
# 0.1 
#    * created
#
# 0.2
#    * added -h -V -v options
#    * changed function isTime to isNumerical
#      * changed name and changed exit to return
#    * cleaned usage function
#
#

use Getopt::Std;

$version = "0.2";

# prints out usage information
sub usage
{
	print "\nSubShifter v$version\n\n";
	print "Usage: subshifter.pl -t <msec> -i <ifile> [-o <ofile>] [-h] [-m] [-v] [-V]\n\n";
	print "  -t     time in milliseconds to shift subtitles. Must be > 0\n";
	print "  -i     filename to reading\n";
	print "  -o     filename to writing. If no name is given stdout is used.\n";
	print "  -d     used to decrease shiftingtime \(subtime-time\)\n";
	print "  -h     prints this help\n";
	print "  -v     verbose mode\n";
	print "  -V     prints only version information\n\n";
}

# is numerical value
# decimal numbers are not allowed eighter
sub isNumerical
{
	($test) = @_;
	if (!($test !~ m/\D/) )
	{
		&usage();
    		return 0;
	}
	return 1;
}

# Get options
getopt('tio', \%opts);

$input = $opts{'i'};
$output = $opts{'o'};
$time = $opts{'t'};

if($opts{'V'})
{
	print "\nSubShifter v$version\n\n";
	exit 0;
}

# help
if($opts{'h'})
{
	&usage();
	exit 0;
}

# Some tests are arguments ok
if(!$time || !$input )
{
	&usage;
	exit 1;
}

if (!(-e $input))
{
	&usage();
	exit 2;
}

if(!&isNumerical($time))
{
	exit 3;
}

# decrease
if($opts{'d'})
{
	$time = -$time;
}

#print some information
if($opts{'v'})
{
print "Time to shift: $time \n";
print "from $input\n";
print "to file $output\n\n";
}

open IFILE, "$input" or die("Couldn't open $input\n") ;

# if user gave output file
# set sdtout to print this
if($output)
{
	open STDOUT, ">$output" or die("Couldn't open $output\n") ;
}

# reads whole file line by line
# and writes it to stdout
while($test =  readline(IFILE))
{
	$line = $test;
	@line_t1 = split(/}/, $line);
	@line_t2 = split(/{/, $line_t1[0]);
	@line_t3 = split(/{/, $line_t1[1]);
	$line_t2[1] += $time;
	$line_t3[1] += $time;

	# drops negatives out ;)
	if($line_t2[1] > 0 )
	{

		print "{$line_t2[1]}";
		print "{$line_t3[1]}";
		print "$line_t1[2]";
	}
}

#close everything
close IFILE;

if($output)
{
	close STDOUT;
}


