#!/bin/sh

# disable filename globbing

 echo Content-type: text/html
 echo
 BASE=`pwd`
{
APPLDIR=$BASE/appl
DATADIR=$BASE/data
PATH=$PATH:$BASE/ihd/bin:.
export PATH APPLDIR DATADIR
T=/tmp/T$$
T1=/tmp/T1$$
T2=/tmp/T2$$
splash >$T
awk -F= ' BEGIN { ret=sprintf("%c",13) }
$0=="" { next }
$1=="T00" { next }
substr($1,1,5)=="forms" && $2=="" { next }
/DOCforms/ { next }
{ wh="" }
substr($1,1,5)=="forms" && index($0,ret) >0 {
printf "%s",$0
        while (wh=="")
        {
                if (getline <= 0) wh=1
                if(substr($1,1,5)=="forms") 
                if (index($0,ret)==0)  { printf "\n%s\n",$0;wh=1 }
                else printf "%s",$0
                else  printf "%s",$0
        }
}
wh=="" && $2!="" && $1!="T00" ' $T > $T1
QRY=`awk -F= ' substr($1,1,1)== "B" {print $2} ' $T1 `
frm=`awk -F= ' index($1,"H00") >0  {print $2} ' $T1 `
if [ "$QRY" = Consultar ]
then
	COMMAND=`awk -F= ' BEGIN { printf "./ihd/bin/ihmq forms " }
	$1!="B1" {
	if (NR==1 && substr($1,length($1)-1) !="00") printf "H00^ "
	if (substr($1,1,3)=="DOC") printf "D%s^%s ",substr($1,length($1)-1),adv($2)
	else printf "H%s^%s ",substr($1,length($1)-1),adv($2)
}
function adv(txt) { while (substr(txt,1,1)==" ") txt=substr(txt,2); return (txt) }
END {
print "" } ' $T1 `
$COMMAND | sort -t\^ -k2 -k1 -u  >$T2
NF=`awk ' END { print NR } ' $T2`
if [ $NF = 1 ]
then
		REG=`awk -F"^" ' { print $1 } ' $T2`
		./formsget.cgi $REG
	else
	./formslist.cgi $T $T2
	fi
fi
if [ "$QRY" = Actualizar ]
then
	COMMAND=`awk -F= ' END { printf "./ihd/bin/ihmu forms %s\n","'"$T2"'" } ' `
	awk -F= '
	/formsH/ { printf "H%s%s\n",substr($1,length($1)-1),substr($0,10) }
	/formsD/ { printf "D%s%s\n",substr($1,length($1)-3),substr($0,12) }
	' $T1 > $T2
echo -n " " >>$T2
	$COMMAND
	cat ../forms
fi
if [ "$QRY" = FRM ]
then
	COMMAND=`awk -F= ' END { printf "./ihd/bin/ihmu forms %s\n","'"$T2"'" } ' `
	awk -F= '
	/formsH/ { printf "H%s%s\n",substr($1,length($1)-1),substr($0,10) }
	/formsD/ { printf "D%s%s\n",substr($1,length($1)-3),substr($0,12) }
	' $T1 > $T2
echo -n " " >>$T2
	$COMMAND
	./pwb $frm
	cat ../forms
fi
 } 2> ./error/forms.err
rm $T $T1 $T2
