#!/bin/bash

source bash_ui
source bash_f_dlg
source bash_sg_dlg
source bash_pr_dlg

make_ps() {
    cat << EOF
%!PS
% Written by Helge Blischke, see
% http://groups.google.com/groups?ic=1&selm=3964A684.49D%40srz-berlin.de
%
% The following 2 procs encapsulate the jobs to be processed
% much as is done with EPS images:
/_begin_job_
{
        /tweak_save save def
        /tweak_dc countdictstack def
        /tweak_oc count 1 sub def
        userdict begin
}bind def

/_end_job_
{
        count tweak_oc sub{pop}repeat
        countdictstack tweak_dc sub{end}repeat
        tweak_save restore
}bind def

% Now, add your jobs like this:

EOF
    local -i i=0
    while [ $i -lt ${#src_list_array[*]} ]; do
        echo "_begin_job_"
        echo "(${src_dir_array[$i]}/${src_list_array[$i]}) run"
        echo "_end_job_"
        echo
        let i++
    done

    echo "% and so on."
}

##################################################
#
#  The main procedure
#
##################################################
root_path=${0%[/]*}
export PATH=$PATH:/bin:$root_path
cd "$root_path"
recent_dir="`pwd`"
if [ -f .merge_pdf.cfg ]; then
    recent_dir="$(< .merge_pdf.cfg)"
fi
tty_init
run_src_gather_dialog "[PDF Merge]" "Merge" "Merge pdf files" '*.[Pp][Dd][Ff]' '*.pdf'
if [[ "$_KEY_" == [Mm] ]]; then
    run_file_dialog "[PDF Merge] --> Save as (*.pdf)" "$recent_dir" "*.[Pp][Dd][Ff]" "new"
    if [ "${file_dialog_file%%*.[Pp][Dd][Ff]}" != "" ]; then
        file_dialog_file="${file_dialog_file}.pdf"
    fi
    if [[ "$_KEY_" == [Oo] ]]; then
        process_dlg_title="[PDF Merge]"
        load_process_dlg_ui
        show_status "Merging the pdf files..." "Please wait..."
        error_log=`make_ps | ps2pdf - "$file_dialog_dir/$file_dialog_file" 2>&1 | tee`
        if [ "$error_log" == "" ]; then
            show_status "Merging the pdf files...OK!" "Press any key to exit..."
        else
            show_status "Merging the pdf files...FAIL!" "Please see the error log"
            echo 
            echo "================== error log ========================="
            echo "$error_log"
            echo
            echo -n "Press any key to exit ..."
        fi
        read_key
    fi
fi
tty_restore
echo "$recent_dir" > .merge_pdf.cfg
exit 0


