#!/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
if [ "$1" = FromAnls ]
then
	R=`awk -F= ' $1=="vouchH00" { if(substr($2,1,1) ==" ") printf "tmpB/S%d",$2 } ' $T`
	if [ "$R" != "" ]
	then
		A=../js/tmp/AS$$.js
>$A
		awk -F"^" ' FILENAME == ARGV[1] { if (substr($1,1,1)=="C") r[substr($1,2)+0]=1
		if(index($1,"vouchH00")) ct=substr($0,length($0)-4)
		next
		}
		r[FNR]==1 {
			printf "document.vouchform.vouchD%.2d00.value=\"%s\"\n",z,ct
			printf "document.vouchform.vouchD%.2d01.value=\"%s\"\n",z,ct
			printf "document.vouchform.vouchD%.2d02.value=\"%s\"\n",z,$5
			printf "document.vouchform.vouchD%.2d03.value=\"%s\"\n",z,$7
			printf "document.vouchform.vouchD%.2d04.value=\"%s\"\n",z,$6
			printf "document.vouchform.vouchD%.2d05.value=\"%s\"\n",z,$8
			printf "document.vouchform.vouchD%.2d06.value=\"%s\"\n",z,$9
			printf "document.vouchform.vouchD%.2d07.value=\"%s\"\n",z,$10
			printf "document.vouchform.vouchD%.2d08.value=\"%s\"\n",z,$11
			z++
		}
		END {
			printf "swapout()\n"
		} ' $T $R > $A
		rm $T
#sh show $A
#exit
awk ' { print }
/mtpdoc.js/ { printf "<script language=\"Javascript\" src=\"%s\"> </script>\n","'"$A"'" }
' ../vouch.htm
		exit
	fi
fi
awk -F= ' BEGIN { ret=sprintf("%c",13) }
$0=="" { next }
$1=="T00" { next }
substr($1,1,5)=="vouch" && $2=="" { next }
/DOCvouch/ { next }
{ wh="" }
substr($1,1,5)=="vouch" && index($0,ret) >0 {
printf "%s",$0
        while (wh=="")
        {
                if (getline <= 0) wh=1
                if(substr($1,1,5)=="vouch") 
                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= ' $1== "B1" {print $2} ' $T1 `
if [ "$QRY" = Consultar ]
then
	COMMAND=`awk -F= ' BEGIN { printf "./ihd/bin/ihmq vouch " }
	$1!="B1" {
	if (NR==1 && substr($1,length($1)-1) !="00") printf "H00^ "
	if (substr($1,6,1)=="D") 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
#sh show $T1
NF=`awk ' END { print NR } ' $T2`
if [ $NF = 1 ]
then
		REG=`awk -F"^" ' { print $1 } ' $T2`
		./vouchget.cgi $REG
	else
	./vouchlist.cgi $T $T2
	fi
fi
if [ "$QRY" = Actualizar ]
then
	COMMAND=`awk -F= ' END { printf "./ihd/bin/ihmu vouch %s -N1\n","'"$T2"'" } ' `
	awk -F= '
	/vouchH/ { printf "H%s%s\n",substr($1,length($1)-1),substr($0,10) }
	/vouchD/ { printf "D%s%s\n",substr($1,length($1)-3),substr($0,12) }
	' $T1 > $T2
echo -n " " >>$T2
	$COMMAND 
	cat ../vouch
fi
 } 2> ./error/vouch.err
cat ./error/vouch.err
rm $T $T1 $T2
