#!/bin/bash

#  Template HTML file.

template='template.html'

keylist='keylisth.new'

#  Date of issue of SOFA product.
issue_date=`cat issue_date`

#  Processing date for `Created:' line.
process_date="2017-04-20"

#  Processing directory.
source_dir="2017_0420_C"

#  Loop over source files in sofa directory

for source in `find . -name "*.h"` ; do

   if [ -e $source ] ; then
      echo "Processing file $source"

#  Strip name of source file.
      file=`basename ${source} ".h"`

      echo "file = $file"

#  Make routine name upper-case.
#     routine=`echo ${file} | tr '[a-z]' '[A-Z]'`

# This line makes the first character of file upper case.

      routine=`echo ${file} | perl -pe 's/^(.{0})(.)/$1\U$2/;'`

      echo "routine = $routine"

#  Initialise for search.
      create_date=''
      library=''
      section=''
      title=''
      description=''

#  Find routine in key file.

#      description=`grep :${routine}: ${keylist}`

#      if [ "$file" = "t_sofa_c" ]; then
         routine=`echo ${file} | tr '[a-z]' '[A-Z]'`
         description=`grep :${routine}.h: ${keylist}`
#      fi

#  Process description if found.

      if [ ! -z "${description}" ] ; then
         create_date=`echo ${description} | awk -F: '{print $1}' - ` 
         library=`echo ${description} | awk -F: '{print $2}' - ` 
         section=`echo ${description} | awk -F: '{print $3}' - `
         title=`echo ${description} | awk -F: '{print $5}' - `

#        echo $description
#        echo $library $section $routine $title

#  Create the file from the template.

         sed -e s#ISSUEDATE#"$issue_date"# \
             -e s#PROCESSDATE#"$process_date"# \
             -e s#SOURCEDIR#"$source_dir"# \
             -e s#CREATEDATE#"$create_date"# \
             -e s#ROUTINE#"$routine"# \
             -e s#LIBRARY#"$library"# \
             -e s#SECTION#"$section"# \
             -e s#TITLE#"$title"# \
             -e s#FILE#"$file"# \
          < ${template} > ${file}_h.html


#
      else
         echo "No description for $file / $routine"

      fi

   else 
      echo "File $source - unable to process!"
   fi

done

#  Finished.
exit
#.