#!/bin/sh
#######  Arguments #######
# 1             - path to input file
# 2 and above   - the times in decimal form


#ffmpeg=`echo $0 | sed "s/subtoolsscript.sh/ffmpeg/"`
ffmpeg="$1"/ffmpeg/ffmpeg

#echo $ffmpeg



shift
inputFile="$1"
shift
saveDirectory="$1"
shift


wPadding=64
wPadding2=`expr $wPadding / 2`
hPadding=48
hPadding2=`expr $hPadding / 2`



for theTime in "$@"
do
	###   Get the crop for the ith text
    theCrop=`"$ffmpeg" -ss $theTime -i "$inputFile" -filter_complex "color=size=1920x1080 [base];[base][0:0]overlay[out]" -map [out] -vcodec mpeg4 -vframes 6 -f matroska -loglevel quiet - | "$ffmpeg" -i - -vf "cropdetect=16:16:0" -an -f null - 2>&1 | awk '/crop/ { print $NF }' | head -n 1 | cut -d "=" -f 2`

#echo $theTime
#echo $theCrop

	cropWidth=`echo "$theCrop" | cut -d ":" -f 1`
    cropWidth=`expr $cropWidth + $wPadding`
    cropHeight=`echo "$theCrop" | cut -d ":" -f 2`
    cropHeight=`expr $cropHeight + $hPadding`
    cropX=`echo "$theCrop" | cut -d ":" -f 3`
    cropX=`expr $cropX - $wPadding2`
    cropY=`echo "$theCrop" | cut -d ":" -f 4`
    cropY=`expr $cropY - $hPadding2`
    theCrop=`echo $cropWidth:$cropHeight:$cropX:$cropY`

# if the cropWidth is really small or negative, then no text was found, so don't make a tif
    if [ "$cropWidth" -lt 2 ]
    then
#echo negative
# "$ffmpeg" -ss $theTime -i "$inputFile" -filter_complex "color=size=1920x1080 [base];[base][0:0]overlay=(main_w-overlay_w)/2: main_h-overlay_h[out]" -map [out] -pix_fmt rgb24 -vcodec tiff -vframes 1 -loglevel quiet -y "$saveDirectory"tempTif."$theTime".tif
        echo "no text" >> "$saveDirectory"tempTif."$theTime".tif

    else
        "$ffmpeg" -ss $theTime -i "$inputFile" -filter_complex "color=size="$cropWidth"x"$cropHeight" [base];[0:0] crop="$theCrop" [subInitialize];[base][subInitialize]overlay=(main_w-overlay_w)/2: main_h-overlay_h[out]" -map [out] -pix_fmt rgb24 -vcodec tiff -vframes 1 -loglevel quiet -y "$saveDirectory"tempTif."$theTime".tif
    fi
done


