#!/bin/bash

if [[ "$1" != "" ]]; then
    repertoire="$1";
else
    echo "enter the complete path of the directory where the image sequence (with holes) is"
    read repertoire
fi
if [[ ! -d "$repertoire" ]]; then
    echo "error : could not find the image sequence directory at $repertoire"
    exit;
fi
echo "directory of the image sequence : $repertoire"


if [[ "$2" != "" ]]; then
    imagenoire="$2";
else
    echo "enter the complete path of the black image that will be used to fill the gap in the image sequence"
    read imagenoire
fi
echo "black image : $imagenoire"

if [[ ! -a "$imagenoire" ]]; then
    echo "error : could not find the black image at path $imagenoire"
    exit;
fi


echo ; echo 

cd "$repertoire"
if [[ "$?" != "0" ]]; then
    echo "could not change directory to $repertoire"
    exit
fi
echo 'processing'

length=0;
holefound=0;
OLDIFS=$IFS
IFS="
"
for FILENAME in `find . -name '*.dpx' -not -path '*bob_*' -maxdepth 1`; do
    let compteur=$compteur+1
    numero=`echo $FILENAME | perl -pi -e 's/.*?(\d+)\.dpx/$1/g'`
    if [[ "$length" = "0" ]]; then
	FILENAME=`basename $FILENAME`
	length=${#numero}
	base=`echo $FILENAME | perl -pi -e 's/(.*?)(\d+)\.dpx/$1/g'`
	echo "length : $length ; base : $base"
    fi

    numero=`echo $numero|sed 's/^0*//'`
    echo $numero
    if [[ "$compteur" -gt "1" ]];then
	let anciennumerotheorie="$numero"-1;
	let difference="$anciennumeropratique-$anciennumerotheorie";
	if [[ ! "$difference" -eq 0 ]];then
	    let holefound=$holefound+1;
	    echo "hole found at frame number $numero ($FILENAME)"
	    while [[ "$anciennumeropratique" -lt "$anciennumerotheorie" ]];do
		let anciennumeropratique=$anciennumeropratique+1
		nomimagenoire="$base"`printf %0""$length""d $anciennumeropratique`".dpx"
		ln -v "$imagenoire" "$nomimagenoire"
	    done
	fi
    fi

    anciennumeropratique=$numero
done
IFS=$OLDIFS
echo ; echo 
echo "done"
echo "found $holefound holes in the image sequence in $repertoire"
echo ; echo 