#!/bin/sh
#
# split_video finput foutput start_time duration 
#
# D. Edwards <davidbtdt@gmail.com> Sat Sep 22 16:16:55 PDT 2012

if [ $# -eq 0 ]; then
    echo
    echo " Split video file keeping the same format."
    echo
    echo "Usage: split_video input_file_name output_file_name start_time stop_time"
    echo
    echo "   where <start_time> and <stop_time> are in HH:MM:SS format."
    echo "   NOTE: Leading zeros are required."
    echo
    echo "If <start_time> = 0, the video will not be trimmed at the beginning."
    echo "If <stop_time> = 0, the end of the video will not be trimmed."
    echo
    echo "Example: split_video big.mpg small.mpg 0:05:00 0:25:30"
    echo "Example: split_video big.mpg small.mpg 0 0:30:30"
    echo
    echo "*** This uses -y to ffmpeg so that it will overwrite files ***"
    echo
    echo "Use Free Video Dub v2.0.14 build 903 for accurate times."
    echo
    echo "Depending on where the leading split is, ffmpeg may not keep the video"
    echo "and audio in synch. By trial and error, <start_time> can be adjusted"
    echo "and the resulting file checked, until they are in synch. MP4 files are"
    echo "especially prone to getting out of synch."
    echo
    exit 1
fi


if [ $3 == '0' ]; then
	ffmpeg -y -i "$1" -vcodec copy -acodec copy -t $4 "$2"
	exit 0
fi

if [ $4 == '0' ]; then
	ffmpeg -y -i "$1" -ss $3 -vcodec copy -acodec copy "$2"
	exit 0
fi

iHH=${3:0:2}
iMM=${3:3:2}
iSS=${3:6}

fHH=${4:0:2}
fMM=${4:3:2}
fSS=${4:6}

let iSEC=3600*$iHH+60*$iMM+$iSS
let fSEC=3600*$fHH+60*$fMM+$fSS
#echo "iHH = $iHH, iMM = $iMM, iSS = $iSS -> $iSEC"
#echo "fHH = $fHH, fMM = $fMM, fSS = $fSS -> $fSEC"

let DUR=$fSEC-$iSEC
#echo "Duration = $DUR"

let dHH=$DUR/3600
let dMM=($DUR-3600*$dHH)/60
let dSS=$DUR-3600*$dHH-60*$dMM
#echo "dHH = $dHH, dMM = $dMM, dSS = $dSS"

ffmpeg -y -i "$1" -ss $3 -vcodec copy -acodec copy -t $dHH:$dMM:$dSS "$2"

