#!/usr/bin/env ruby
# RUBY PROGRAM _________________________________________________ vim:sw=4:tw=79
#
# *      project : adjustSrtTiming
# *         file : adjustSrtTiming.rb
# *       author : Jakob Schmid
# *    commenced : 2006-12-05
# * last changes : 2006-12-05
# *        notes : I saw no reason for supporting millisecond timing, but if
#                  someone needs it, I'll make it :)
# _____________________________________________________________________________

if ARGV.length != 2 then
    puts "usage: adjustSrtTiming.rb file.srt seconds"
    puts "  - adds [seconds] to the timing of the subtitle file."
    puts "    [seconds] may be negative."
    exit
end
seconds = ARGV[1].to_i

class TimeStamp
    attr_accessor :h, :m, :s, :ms

    def initialize(timeString = "00:00:00,000")
        # parse string into (hour,minute,second,millisecond) values
        @h, @m, @s, @ms = timeString.split(/:|,/).collect{|s| s.to_i}
    end
    def to_s() "%02d:%02d:%02d,%03d" % [@h,@m,@s,@ms] end
    def +(s)
        t = clone   # copy self
        t.s += s    # add seconds
        t.normalize # fix eventual second overflow
        return t
    end
    def normalize
        @m += @s / 60 ; @s %= 60 # add overflowed seconds to minutes
        @h += @m / 60 ; @m %= 60 # add overflowed minutes to hours
    end
end

IO.readlines(ARGV[0]).each do |line|
    if line =~ /\d+:\d+:\d+,\d+ --> \d+:\d+:\d+,\d+/ then
        startTimeString, endTimeString = line.strip.split(/ --> /)
        startTime = TimeStamp.new(startTimeString)
        endTime   = TimeStamp.new(endTimeString)
        startTime += seconds ; endTime += seconds
        puts "#{startTime} --> #{endTime}"
    else puts line
    end
end
