#!/bin/bash

if [ $# != 5 ]; then
    echo -e "USAGE:\n$0 path_to_subtitle P1 P2 P3 P4\n\n"
	echo "You must give 4 points for this program to work, each point is the time in seconds that the sentece begins, therefore this expresssion is valid: \"hour*3600 + min*60 + sec\""
	echo "Consider the following example bellow, you should reffer to this point with the number 4844 = 1*3600 + 20*60 + 44"
	echo "   203"
	echo "   01:20:41,658 --> 01:20:44,991"
	echo "   Hello there dear friends"
	echo "The first two points are from the current subtitle you have and the last two are from the desired subtitle."
	echo "CURRENT SUBTITLE:"
	echo "       P1                  P2"
	echo "-------|--------(...)------|--"
	echo "----|----------(...)------------|--"
	echo "   P3                          P4"
	echo "DESIRED SUBTITLE"
	echo "This means you wish P1 was P3 and P2 was P4"
	echo "Its is recomended that P1 and P3 are in the begining of the subtitle and P2 and P4 are at the end of the subtitle"
    exit 1
fi


awk -v P1=$2 -v P2=$3 -v P3=$4 -v P4=$5 '
BEGIN {
	offset = P3 - P1;
	common_point = P3;
	speed_adjust = (P4 - P3) / (P2 - P1);
    print offset;
    print common_point;
    print speed_adjust;
    FS=":|,| --> ";
}

#Case the line is a time stamp
$0 ~ /[0-9]+:/ {
#   offset=5;
#   common_point=119;
#   speed_adjust=4434/4250;

    # Doing the adjust for the time that a frase begins
    time=($1*3600+$2*60+$3)+offset;
    time=((time-common_point)*speed_adjust)+common_point;
    hour=time/3600;
    min=(time%3600)/60;
    sec=(time%3600)%60;
    printf ("0%d:%02d:%02d,%s", hour, min, sec,$4);

    printf (" --> ");

    # Doing it again for the time the frase ends
    time=($5*3600+$6*60+$7)+offset;
    time=((time-common_point)*speed_adjust)+common_point;
    hour=time/3600;
    min=(time%3600)/60;
    sec=(time%3600)%60;
    printf ("0%d:%02d:%02d,%s\n", hour, min, sec,$8);
}

#Else just print the line
$0 !~ /[0-9]+:/ {
    print $0;
}
' $1


