#!/bin/sh
#
# NAME
#   extractPod: extract POD blocks from Perl source files.
#

epfUsage()
{
  if [ $# = 0 ]; then
    echo "usage: extractPodFromFile in_file"
    exit 10
  fi
}




openOutputFile ()
{
  if [ ! -e $1 ]; then
    echo "" > $1
    if [ $? != 0 ]; then
      echo "openOutputFile: ERROR: could not write to '$1'"
      exit 20
    fi
  else
    echo "extractPodFromFile: ERROR: file '$1' exists."
    echo " Remove and that file and re-run this script."
    exit 21
  fi
}




extractPodFromFile ()
{
  epfUsage $* ; in_file=$1  ; shift

  if [ ! -r $in_file ]; then
    echo "extractPodFromFile: ERROR: can not read file '$in_file'"
    exit 30
  fi

  false=false
  in_pod_block=$false

  out_file=${subdir}/${in_file}${ext}
  openOutputFile $out_file

  line_index=0
  lines_in_file=`cat $in_file | wc -l`

  while expr $line_index \< $lines_in_file > /dev/null
  do
    line_index=`expr $line_index + 1`

    line_text=`head -$line_index $in_file | tail -1`

    if [ $? != 0 ]; then
      echo "extractPodFromFile: ERROR: failed to read line."
      exit 31
    fi

    subroutine_name=`echo $line_text | grep '^sub' | sed -e 's/^sub *//'`
    if [ "$subroutine_name" != "" ]; then
      echo "extractPodFromFile: found sub '$subroutine_name' at line $line_index"
      out_file=${subdir}/${subroutine_name}${ext}
      openOutputFile $out_file
    fi

    cut_match=`echo $line_text | grep '^=cut'`
    if [ "$cut_match" != "" ]; then
      in_pod_block=$false
      echo "extractPodFromFile: left pod block at line $line_index"
    fi

    if [ $in_pod_block != $false ]; then
      echo "$line_text" >> $out_file
    fi

    pod_match=`echo $line_text | grep '^=pod'`
    if [ "$pod_match" != "" ]; then
      in_pod_block=true
      echo "extractPodFromFile: entered pod block at line $line_index"
    fi
  done
}




usage ()
{
  if [ $# = 0 ]; then
    echo "usage: `basename $0` list_of_perl_files"
    echo "  Each file shoudl contain at least one POD block."
    exit 40
  fi
}



subdir=Pod

if [ ! -d "$subdir" ]; then
  mkdir $subdir
fi

ext=.pod
ext=.txt
for cl_file in $* ; do
  extractPodFromFile $cl_file $ext
done
