#!/bin/bash

if [ $# -eq 4 ]; then
	file=$1
	dirpm=$(dirname "$file")
	outFile=$2
	language=$3
	format=$4
	pdf=1;
else
	if [ $# -eq 6 ]; then
		file=$1
		dirpm=$(dirname "$file")
		outFile=$2
		firstPage=$4
		lastPage=$5
		language=$3
		format=$6
		pdf=0
	else
		if [ $# -eq 5 ]; then
			file=$1
			dirpm=$(dirname "$file")
			outFile=$2
			language=$3
			format=$4
			pdf=1;
			pageList=$5
			fromList=1;
		else
			notify-send 'KBookocr' "Input ERROR"
			exit
		fi
	fi
fi

ext=${file##*.}
filename=$(basename "$file")
fname=${filename%.*}

function f2ocr {
	notify-send 'KBookocr' "Starting OCR"
	for nm in $(seq -f %04g $pagenum) ; do
		ocr=$(cuneiform -f $format -l $language "$workdir/image-$nm.png" -o "$workdir/text-$nm.txt")
	done
	cat "$workdir"/text-*.txt > "$outFile"
	rm -rf "$workdir"
	notify-send 'KBookocr' "OCR is done: $outFile"
}


function f2ocr2 {
	notify-send 'KBookocr' "Starting OCR"
	for nm in $(seq -f %04g $pagenum) ; do
		if [ "$nm" -le "$lastPage" -a "$nm" -ge "$firstPage" ]; then
			ocr=$(cuneiform -f $format -l $language "$workdir/image-$nm.png" -o "$workdir/text-$nm.txt")
		fi
	done
	cat "$workdir"/text-*.txt > "$outFile"
	rm -rf "$workdir"
	notify-send 'KBookocr' "OCR is done: $outFile"
}

function f2ocr3 {
	notify-send 'KBookocr' "Starting OCR"
	for nm in "$pageList" ; do
		ocr=$(cuneiform -f $format -l $language "$workdir/image-$nm.png" -o "$workdir/text-$nm.txt")
	done
	cat "$workdir"/text-*.txt > "$outFile"
	rm -rf "$workdir"
	notify-send 'KBookocr' "OCR is done: $outFile"
}

### Working with pdf file

if [ "$ext" == "pdf" ]; then
	workdir="$HOME/.tmp_pdf"
	mkdir -p "$workdir"
	pagenum=$(pdfinfo "$file" | awk '/Pages/' | awk '{print $2}' )
	notify-send 'KBookocr' "Converting to png: $filename"
	gs -r150 -q -sDEVICE=pngmono -dDOINTERPOLATE -dNOPAUSE -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -sOutputFile="$workdir/image-%04d.png" -- "$file"
	if [ $# -eq 4 ]; then
		f2ocr
	else
		if [ $# -eq 5 ]; then
			f2ocr3
		else
			f2ocr2
		fi
	fi
        

### Working with djvu file

elif [ "$ext" == "djvu" ]; then
	workdir="$HOME/.tmp_djvu"
	mkdir -p "$workdir"
	notify-send 'KBookocr' "Converting to png: $filename"
	if [ $# -eq 4 ]; then
		ddjvu -format=tiff -mode=black -quality=100 "$file" "$workdir/$fname.tiff"
	else
		ddjvu -page="$firstPage-$lastPage" -format=tiff -mode=black -quality=100 "$file" "$workdir/$fname.tiff"
	fi
	tiff2pdf -j -b -o "$workdir/$fname.pdf" "$workdir/$fname.tiff"
	pagenum=$(pdfinfo "$workdir/$fname.pdf" | awk '/Pages/' | awk '{print $2}' )
	echo "$workdir/$fname.pdf"
	gs -r150 -q -sDEVICE=pngmono -dDOINTERPOLATE -dNOPAUSE -dTextAlphaBits=4 -dGraphicsAlphaBits=4 -sOutputFile="$workdir/image-%04d.png" -- "$workdir/$fname.pdf"
	#if [ $# -eq 3 ]; then
	f2ocr
	#else
	#f2ocr2
	#fi

### Catching an error

else
	notify-send 'KBookocr' "This file type is not supported: $ext" 
fi
