#!/bin/bash

rm -rf spelling
mkdir spelling
# Get names of all actions and command line tools
../src/lib/plumed --no-mpi manual --action=ABMD > /dev/null 2> spelling/keywords
cat spelling/keywords | grep -v "LIST OF" | awk '{if(NF>0) print $1}' > spelling/pkeys
# Get all the keywords for all actions
while read flag; do
   ../src/lib/plumed --no-mpi manual --action=$flag --spelling > spelling/$flag.psp 2> /dev/null
   cat spelling/$flag.psp | sed -e $'s/_/\\\n/g' | sed -e $'s/-/\\\n/g' | grep -v '[0-9]' | grep -v "help" | awk '{if(NF>0) print $1}' >> spelling/allkeys 
done < spelling/pkeys
# Now reconfigure the keyword list to get rid of troublesome characters
cat spelling/pkeys | sed -e $'s/_/\\\n/g' | grep -v '[0-9]' | sed -e $'s/-/\\\n/g' > spelling/keywords
# And now construct the exclude list for the spell checker
nsafewords=`cat spelling/keywords spelling/allkeys spelling_words.dict | wc -l | awk '{print $1}'`
echo personal_ws-1.1 en $nsafewords > ./spelling/allwords.dict
cat spelling/keywords spelling/allkeys spelling_words.dict >> spelling/allwords.dict

# This is everything we have done thus far
for file in *PP.md automatic/*.txt ../CHANGES/*.md tutorials/*.txt tutorials/*.site tutorials/others/*.txt ; do
    echo Checking spelling for file $file
    splits=`echo $file | sed -e 's/\// /g'`
    nf=`echo $splits | awk '{print NF}'`
    fname=`echo $splits | awk -v n=$nf '{print $n}'` 
    # This is some stuff to get rid of stuff that trips up the spell checker: the equations and the plumed examples 
    cat $file | grep -v "\\image" | grep -v "anchor" | sed -e 's/psi-1//' | sed -e 's/-#//' | sed -e 's/@//' | sed -e 's/&//' | sed -e 's/\vdots//' | 
    awk 'BEGIN{inp=0}{
          if($1=="\\endplumedfile" || $1=="\\f]" || $1=="\\f}" || $1=="\\endverbatim" || $1=="\\endcode"){inp=0;}
          else if($1=="\\plumedfile" || $1=="\\f[" || $1=="\\f{eqnarray*}{" || $1=="\\verbatim" || index($1,"\\code{")!=0 ){inp=1;}
          else if(inp==0){
            skip=0;
            for(i=1;i<=NF;++i){ 
                if(skip==1){ skip=0; }
                else if($i=="\\subsubsection" || $i=="\\cite" || $i=="\\ref" || $i=="\\page" || $i=="subpage" || $i=="\\subpage" || $i=="\\section" || $i=="\\subsection" || $i=="\\link" ){ skip=1; }
                else if(index($i, "\\f$")==0 && index($i,"http")==0 && index($i,".py")==0 ) { printf(" %s",$i); }
            }
            printf("\n");
          }
          }' > spelling/$fname.md

    # Check for spelling mistakes
    tail -n +2 spelling/$fname.md | grep -v "*/" | aspell pipe -H --dont-suggest --personal=./spelling/allwords.dict | grep -v '*' | grep -v "International Ispell" | awk '{if(NF>0) print $0}' > spelling/$fname.err
    nerrors=`wc -l spelling/$fname.err | awk '{print $1}'`
    # Crash out if there are spelling mistakes
    if [ $nerrors -gt 0 ] ; then 
       echo "Found spelling mistakes in documentation file $file" 
       cat spelling/$fname.err
       exit 1
    fi
done
