#!/bin/bash




ORIG_HTML=$1
LINE_BEGIN=$2
IMPROVED_FILENAME_LIST="量子ls.txt"
HTML_IMPROVED="量子improved.html"
TMP0_FILE="tmp0.txt"
TMP1_FILE="tmp1.txt"
TMP2_FILE="tmp2.txt"
ERROR_LOG1="error_in_exist_log.txt"
ERROR_LOG2="replace_error_log.txt"

echo_n_left_spaces()
{
   local CC=0
   while [ ${CC} -lt $1 ] ; do

      echo -n " "

      let CC=CC+1
   done

}

blink_msg()
{
   echo -n -e "\e[01m\e[5m$1\e[0m"
}
## Error to warning with blink
function bred(){
    echo -e "\033[31m\033[01m\033[05m[ $1 ]\033[0m"
}

## Error to warning with blink
function byellow(){
    echo -e "\033[33m\033[01m\033[05m[ $1 ]\033[0m"
}



sound_msg()
{
   echo -n $1
   echo -n -e "\a"
}

greenmsg()
{
	echo -n -e  "\e[32m$1\e[0m"
}
redmsg()
{
	echo -n -e  "\e[31m$1\e[0m"
}
boldmsg()
{
	echo -n -e  "\e[1m$1\e[0m"
}


# Shared functions for RosBE-Unix components
# Part of RosBE for Unix-based Operating Systems
# Copyright 2009 Colin Finck <mail@colinfinck.de>
#
# Released under GNU GPL v2 or any later version.

# Print a message in a bold font
#  Parameter 1: The message
#  Parameter 2: Optional additional parameters for "echo"
boldmsg2()
{
	echo -n -e $2 "\e[1m$1\e[0m"
}

# Print a message in green color
#  Parameter 1: The message
#  Parameter 2: Optional additional parameters for "echo"
greenmsg2()
{
	echo -n -e $2 "\e[32m$1\e[0m"
}

# Print a message in red color
#  Parameter 1: The message
#  Parameter 2: Optional additional parameters for "echo"
redmsg2()
{
	echo -n -e $2 "\e[31m$1\e[0m"
}
bluemsg2()
{
	echo -n -e $2 "\e[34m$1\e[0m"
}
bluemsg()
{
	echo -e $2 "\e[34m$1\e[0m"
}

result_check2()
{
	if [ $? -ne 0 ]; then
		redmsg "$1 FAILED"

		echo "Aborted!"
		exit 1
	else
		greenmsg "$1 OK"
	fi
}

result_check()
{
	if [ $? -ne 0 ]; then
		redmsg "FAILED"

		echo "Aborted!"
		exit 1
	else
		greenmsg "OK"
	fi
}




test()
{
while [ true ] ; do
sound_msg hi
#blink_msg test
byellow test
greenmsg no
redmsg   yes
boldmsg  bold
sleep    2
done
}


if [ X"${ORIG_HTML}" = X"" ] ; then 
  echo "Usage: ./improve_quantum_encoding.sh   ORIG_HTML   [LINE_BEGIN]  "
  exit
fi
if [ X"${LINE_BEGIN}" = X"" ] ; then 
  LINE_BEGIN=1
fi


USING_SLASH=0
USING_BACKSLASH=0
VAR="\\\\"
#      
#check slash style 
#
for i in `cat ${ORIG_HTML} | grep -n "/\[" | awk -F ":" '{print $1}'` ; do
      let USING_SLASH+=1
done
for i in `cat ${ORIG_HTML} | grep -n "${VAR}\[" | awk -F ":" '{print $1}'` ; do
      let USING_BACKSLASH+=1
done
echo "Found ${USING_SLASH} /[ s AND ${USING_BACKSLASH} \\[ s"
if [ ${USING_SLASH} -gt 0 ] && [ ${USING_BACKSLASH} -gt 0  ] ; then
     echo "IT IS BAD THAT YOU ARE USING SLASH AND BACKSLASH STYLE IN ONE SAME FILE.exit."
     exit
elif [ ${USING_SLASH} -gt 0 ] ; then
      # deal with entry using slash
     COMMAND="`cat ${ORIG_HTML} | grep -n \"/\[\" | awk -F \":\" '{print $1}'`"
elif [ ${USING_BACKSLASH} -gt 0  ] ; then
      # deal with entry using backslash
     COMMAND="`cat ${ORIG_HTML} | grep -n \"${VAR}\[\" | awk -F \":\" '{print $1}'`"
else
     echo "Nothing to do, exit."
     exit
fi

#      
#check where we should begin
#      
TOTAL=`cat ${ORIG_HTML} | wc -l`
let NUM=LINE_BEGIN
#echo "begin from line $NUM"

ALREADY_DONE=0
if [ -e "${HTML_IMPROVED}" ] ; then
    ALREADY_DONE=`wc -l "${HTML_IMPROVED}" | awk '{print $1}'`
    echo "The HTML to be generated already finished ${ALREADY_DONE} lines."
else
    echo "${HTML_IMPROVED} doesn't exist, to create it and exit."
    touch "${HTML_IMPROVED}"
    exit
fi

ALREADY_DONE_NEXT=0
let ALREADY_DONE_NEXT=ALREADY_DONE+1
if [ $NUM -lt ${ALREADY_DONE_NEXT} ] ; then
    echo "Please delete useless lines in the generating HTML first! exiting...:"
    echo "    REQUESTED: ${NUM} < ${ALREADY_DONE} ALREADY DONE + 1."
    exit
elif [ $NUM -gt ${ALREADY_DONE_NEXT} ] ; then
    echo "You are specifying begin line number out of range! to exit:"
    echo "    REQUESTED: ${NUM} > ${ALREADY_DONE} ALREADY DONE + 1."
    exit
else
    echo "Well, the beginning line number is fine:"
    echo "    REQUESTED: ${NUM} = ${ALREADY_DONE} ALREADY DONE + 1."
fi



#      
# do it.
#      

while ! [ $NUM -gt $TOTAL ] ; do
     echo ""
     CUR_LINE=`cat ${ORIG_HTML}  | sed -n ''$NUM','$NUM' p'  `
     #IMPROVED_FILENAME=`cat ${IMPROVED_FILENAME_LIST}  | sed -n ''$NUM','$NUM' p'`  # placed below
     # handle only a entry
     ENTRY_LINE=`echo "${CUR_LINE}" | grep -e "<li>"`
     if [ X"${ENTRY_LINE}" = X"" ] ; then
         echo "Please simplify the HTML first to have only entry lines left, exiting.."
         exit
     fi
     # try to find "book" name and its file's full path
     #FULL_PATH=`echo ${ENTRY_LINE} | sed 's/^\(.*\)href=\"\(.*\)\">\(.*\)<\/[Aa]><\/li>.*$/\2/g' `
     FULL_PATH=`echo "${ENTRY_LINE}" | sed 's/^\(.*\)href=\"\(.*\)\">\(.*\)<\/[Aa]><\/li>.*$/\2/g' `
              echo "-1.${ENTRY_LINE}"           
              echo "-1.${FULL_PATH}"           
     #FULL_PATH=`echo ${FULL_PATH}`  # try to trim the spaces, but simply this will reduce the spaces among the string, try to modify as below
     FULL_PATH=`echo "${FULL_PATH}" | sed 's/[\ ]*\([^\ ].*[^\ ]\)[\ ]*/\1/g'`  # to trim the spaces
              echo "0.${FULL_PATH}"            # now "${FULL_PATH}" can be used
     FILE_NAME=`echo "${FULL_PATH}" | sed 's/^\(.*\)\/\([^\/][^\/]*\)$/\2/g'`
              echo "1.${FILE_NAME}"
     # still at some places we use windows' backslashes, to check this
     #STR_CHECK=`echo "${FILE_NAME}" | grep -e '\\'`  # needs single quote here, still of problem in bash file
     VAR="\\\\"
     STR_CHECK=`echo "${FILE_NAME}" | grep -e "${VAR}"`  # needs this method
     if [ X"${STR_CHECK}" != X"" ] ; then
          FILE_NAME=`echo "${FILE_NAME}" | sed 's/^\(.*\)\\\\\([^\\\\][^\\\\]*\)$/\2/g'`  
     fi
              echo "2.${FILE_NAME}"
     # for checking existance
     FULL_PATH_NO_PROTOCOL=`echo  "${FULL_PATH}" | sed 's/\(.*\):\/\/\(.*\)/\2/g'`
     ./check_existance.bat "${FULL_PATH_NO_PROTOCOL}"   # the .bat save error log in "error_in_exist_log.txt", check it.

     # Now the real job
     echo "${NUM}:TODO:${FILE_NAME}" 
     IMPROVED_FILENAME=`cat ${IMPROVED_FILENAME_LIST}  | sed -n ''$NUM','$NUM' p'`
     #echo "  Entry is ${ENTRY_LINE}"
     #echo "  Original file name is ${FILE_NAME}"
     #echo "  Trying to replace to ${IMPROVED_FILENAME}..."
     
     #echo "${ENTRY_LINE}" | sed 's#'${FILE_NAME}'#bbbb\.pdf#'  >>  ${HTML_IMPROVED}

     echo "${ENTRY_LINE}"  > ${TMP0_FILE}
     echo "${FILE_NAME}"  >> ${TMP0_FILE}
     echo "${IMPROVED_FILENAME}"  >> ${TMP0_FILE}
     
     rm -f ${ERROR_LOG2}
     # using c program compiled with "gcc -finput-charset=UTF-8 -fexec-charset=UTF-8 -fwide-exec-charset=UTF-8 -o test replace_one_line_utf-8.c"
     ./replace_one_line_utf-8   2>  ${ERROR_LOG2} | tail -n 1 >>    ${HTML_IMPROVED}  
     log_len=`wc -L ${ERROR_LOG2} | awk '{print $1}'`
     if  [  $log_len -gt 0  ] ; then
        echo "meet error in calling c program, check ${ERROR_LOG1}. exit.."
        exit
     fi
     echo "-----------------------------------------------------------------------"
     
                 let NUM+=1
done

echo "--NOTE: the .bat saves error log in "error_in_exist_log.txt", check it. --"
exit
