#! /bin/sh
# 1. Parameter required : Context Name (Ex. hlqmake long)
# 2. Parameter : AUTHOR
# 3. Parameter : DATE
# If necessary, change AUTHOR, DATE, midas position, template position
#
# 050422	last modif
# 

cmd=`basename $0`
DIR=`pwd`
date=`date '+%d-%h-%y' | tr a-z A-Z`
author=`echo $USER | cut -c 1-2 | tr a-z A-Z`
context=`dirname $DIR` 
context=`basename $context` 
A=%

if [ -n "$1" ]; then
  context=$1
fi

if [ -n "$2" ]; then
  date=$2
fi

if [ -n "$3" ]; then
  author=$3
fi

while :
do
    DIR=`echo $DIR | sed 's/\/[^\/]*$//'`
    if [ -d $DIR/context ]; then
        break
    fi
done

if [ ! -f $DIR/context/$context.ctx ]; then
  echo "${cmd}: Context file $context.ctx not found"
  echo "Usage: $cmd context"
fi

for command in `cat $DIR/context/$context.ctx | \
                grep -i "CREA" | grep -i "/COM" | \
                awk '{if (substr($0,1,1) != "!") {print $2}}' `

do

echo 'Command : '$command

qualif=`echo $command | awk -F/ '{print $2}'`
name=`echo $command | awk '{ FS = "/"} \
     { i = index ($0,"/") - 1} \
     {if (i < 6) print  substr($0,1,i) "_" substr($2,1,4) ".hlq" } \
     {if (i >= 6) print substr ($0,1,6)  substr($2,1,4) ".hlq" } '`

name=`echo $name | tr A-Z a-z`
command=`echo $command | tr a-z A-Z |  sed 's/\//\\\\\//g'`
qualif=`echo $qualif | tr a-z A-Z`

if [ -f $name ]; then
   echo 'Already exists : '$name
else
 echo "% ${A}W% (ESO-IPG) ${A}G% ${A}U%" |
 cat - $DIR/system/unix/template.hlq |   \
 sed -e 's/\&\&COMMAND/'$command'/g'   \
    -e 's/\&\&QUALIF/'$qualif'/g'      \
    -e 's/\&\&FILE/'$name'/g'          \
    -e 's/\&\&AUTHOR/'$author'/g'           \
    -e 's/\&\&DATE/'$date'/g'             \
 > $name

 echo 'Created : '$name

fi

done
