#!/bin/sh

# disable filename globbing

 BASE=`pwd`
APPLDIR=$BASE/appl
DATADIR=$BASE/data
PATH=$PATH:$BASE/ihd/bin:.
export PATH APPLDIR DATADIR

V2=./tmp/V2
V1=./tmp/V1
DP=./tmp/DP
agend=./tmp/agend
./appl/sh/agend  > $agend
# |  1 H00 regist 06 00   0 | 2 H01 pacien 05 51   6 | 3 H02 fechai 10 00  11 |
# |  4 H03 valida 04 00  21 | 5 H04 profes 12 52  25 | 6 H05 fechae 10 00  37 |
# |  7 H06 transs 01 00  47 | 8 H07 transc 20 00  48 | 9 H08 usuari 20 00  68 |
awk -F"^" '  BEGIN { split("31 28 31 30 31 30 31 31 30 31 30 31",m," ") ;inic=f1("'"$1"'") ;fina=f1("'"$2"'") };
function f2(f) { return substr(f,1,2)"/"substr(f,4,2)"/"substr(f,7) }
function f1(f) { return substr(f,7)substr(f,4,2)substr(f,1,2) }
function fv(f) { 
 da=substr(f,1,2) +29
 me=substr(f,4,2)+0
 ye=substr(f,7)
 if (da > m[me]) { da -= m[me]; me++ }
 if (da > m[me]) { da -= m[me]; me++ }
 if(me >12) { me=1; ye++ }
return sprintf("%.2d/%.2d/%.4d",da,me,ye)
}
function tomrw(f) { 
 da=substr(f,1,2)
 me=substr(f,4,2)+0
 ye=substr(f,7)
	da++
 if (da > m[me]) { da =1; me++ }
 if(me >12) { me=1; ye++ }
return sprintf("%.2d/%.2d/%.4d",da,me,ye)
}
FILENAME == ARGV[1] { pr[$1]=$2;mod[$1]=$3;can[$1]=$4; next } 
FILENAME == ARGV[2] { pc[$1]=$0; next } 
pc[substr($2,1,5)]=="" { next }
{ ccic=fv($3)}
f1(ccic) < inic { next }
f1(ccic) > fina { next }
{
	ev[substr($2,1,5)substr($4,1,2)$7]++
	ve[substr($2,1,5)substr($4,1,2)]=1
	vc[substr($2,1,5)]=ccic
}
END {
for (i in pr)
for (j in vc) if(substr(i,1,5)==j)
  printf "%s^%s^%s^%s^%s^%s^%s^%s^%s\n",f1(vc[j]),pc[j],pr[substr(i,1,7)],mod[substr(i,1,7)],can[substr(i,1,7)],ev[i"A"]+0,ev[i"V"]+0,ev[i"C"]+0,can[substr(i,1,7)]-ev[i"C"]

} ' $DP $V1 $agend | sort | awk '{ print substr($0,10) } ' > $V2
