#! /bin/sh

#================================================================
# estxlshtml
# Strip a file of MS-Excel and extract its text as HTML.
#================================================================


# set variables
LANG=C ; export LANG
LC_ALL=C ; export LC_ALL
progname="estxlshtml"
tmpfile="/tmp/$progname-$$.xls"
nulldev="/dev/null"
infile="$1"
outfile="$2"


# show help message
if [ "$1" = "--help" ]
then
  printf 'Strip a file of MS-Excel and extract its text as HTML.\n'
  printf '\n'
  printf 'Usage:\n'
  printf '  %s [infile] [outfile]\n' "$progname"
  printf '  estindex register -xsuf .xls \\\n'
  printf '      application/vnd.ms-excel %s casket\n' "$progname"
  printf '\n'
  exit 0
fi


# function to remove the temporary file
tmpclean(){
  rm -rf "$tmpfile"
}


# function to create the temporary file for input
output(){
  if [ -z "$outfile" ]
  then
    cat
  else
    cat >> "$outfile"
  fi
}


# set the exit trap
trap tmpclean 1 2 3 13 15


# check the input file existence
if [ -n "$infile" ] && [ ! -f "$infile" ]
then
  printf '%s: %s: no such file\n' "$progname" "$infile"
  exit 1
fi


# create the temporary file
if [ -z "$infile" ]
then
  cat > "$tmpfile"
  infile="$tmpfile"
fi


# output the result
xlhtml -xml "$infile" 2> "$nulldev" |
iconv -f UTF-8 -t UTF-8 -c |
awk '
BEGIN {
  title = ""
  lnum = 0
}
{
  if(match($0, /<pagetitle>/) > 0){
    title = $0
    gsub(/<[^>]*>/, "", title)
    sub(/^[ \t]*/, "", title)
    sub(/[ \t]*$/, "", title)
  } else if(match($0, /<cell/) > 0){
    sub(/.*<cell[^>]*>/, "");
    sub(/<\/cell>.*/, "");
    gsub(/<[^>]*>/, " ", $0)
    sub(/^[ \t]*/, "", $0)
    sub(/[ \t]*$/, "", $0)
    body[lnum++] = $0
  }
}
END {
  printf "<html>\n"
  printf "<head>\n"
  printf "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n"
  if(length(title) > 0){
    printf("<title>%s</title>\n", title)
  }
  printf "</head>\n"
  printf "<body>\n"
  for(i = 0; i < lnum; i++){
    if(length(body[i]) > 1){
      printf("<div>%s</div>\n", body[i]);
    }
  }
  printf "</body>\n"
  printf "</html>\n"
}
' |
output


# clean up the temporary directory
tmpclean


# exit normally
exit 0



# END OF FILE
