#!/bin/sh
# Hacked together 2006-09-27 by Peder Hedlund

if [ $# -ne 2 ]; then
  echo ""
  echo " This program changes the timing in a subrip file to delay"
  echo " or place subtitles earlier in time"
  echo ""
  echo " Usage   : $0 <srt-file> [-]<Shift Seconds>,<Shift Thousands>"
  echo " Example : $0 eng.srt -2,013 "
  echo ""
  exit 1
fi  

if [ ! -r $1 ]; then
  echo ""
  echo " Error! File '$1' is not readable "
  echo ""
  exit 1
fi  

OUTFILE=/dev/stdout

# Parse input

AddSec=`echo $2| cut -d, -f1`
AddThs=`echo $2| cut -d, -f2`
if [ ${AddSec} -lt 0 ]; then
  let AddThs=AddThs*-1
fi  

add_time () {

# Prepend with 10# to tell 'let' not to treat it as octal
StartHR=10#`echo $1 | cut -c1-2`
StartMN=10#`echo $1 | cut -c4-5`
StartSK=10#`echo $1 | cut -c7-8`
StartTS=10#`echo $1 | cut -c10-12`

# Recalculate original time to 1/1000 sec
let StartTimeThousand=StartHR*3600000+StartMN*60000+StartSK*1000+StartTS

# Add the desired time change
let NewStartSec=StartTimeThousand+AddSec*1000+AddThs

# Calculate new time :
let NewStartHR=NewStartSec/3600000
let NewStartHRRest=NewStartSec-NewStartHR*3600000

let NewStartMN=NewStartHRRest/60000
let NewStartMNRest=NewStartHRRest-NewStartMN*60000

let NewStartSK=NewStartMNRest/1000
let NewStartTS=NewStartMNRest-NewStartSK*1000

# Print the new time
if [ ${NewStartHR} -lt 10 ]; then
  echo -n 0
fi  
echo -n ${NewStartHR}:
if [ ${NewStartMN} -lt 10 ]; then
  echo -n 0
fi  
echo -n ${NewStartMN}:
if [ ${NewStartSK} -lt 10 ]; then
  echo -n 0
fi  
echo -n ${NewStartSK},
if [ ${NewStartTS} -lt 100 ]; then
  echo -n 0
  if [ ${NewStartTS} -lt 10 ]; then
     echo -n 0
  fi
fi  
echo -n ${NewStartTS}

}

while read var
do
echo "$var" | grep -q --  "-->"
if [ $? -ne 0 ]; then
  echo "$var" >>  $OUTFILE
else
  START=`echo "$var" | cut -c1-12`
  STOP=`echo "$var" | cut -c18-29`
  NEWSTART=`add_time ${START}`
  NEWSTOP=`add_time ${STOP}`
  echo -n $NEWSTART >> $OUTFILE
  echo -n " --> " >> $OUTFILE
  echo  $NEWSTOP >> $OUTFILE
fi
done < $1
