#!/bin/bash/
#The following files must be in the same directory as the QRDA files being processed:
#MeasuresAndReportingParametersWithVariables.xml
#MEASURES-BY-PATIENT.txt
#This script


for MyFile in $(ls -1 /home/nancy/CCR-Template/QRDA/PAT_*_QRDA_V1_0_0-11-04-2010_21.xml);
do 
  StructuredBodyLine=$(grep -n "<structuredBody" "$MyFile" | awk -F: '{ print $1 }')
  echo "structuredBody Line number is $StructuredBodyLine"
  a="$(($StructuredBodyLine+2))"
  b="$(($StructuredBodyLine+5))"
  #In or for Saxon to do its work, the file it works on must be valid, so 3 sets of component/section tags were added to allow for those that will be replaced when the Measures and reporting parameters section is replaced in the file.  They need to be deleted.  The <MeasuresSection/> tag is added in the Header/Parameter document to anchor the replacement. IT will be deleted when the section is put into the file
  echo "a is $a start line to delete for <components>/<section> pairs"
  echo "b is $b end line to delete"
  echo "$MyFile"
  #We can either put this next line in after the fact or before.  Currently it is before
  #sed -in '/structuredBody/{ s/$/\n<MeasuresSection\/>/ }' "$MyFile"
  #sed -in "$c"s/<MeasuresSection\/>//p "$MyFile"
  #MS=$(cat MeasuresAndReportingParametersWithVariables.xml) 
  sed -in "$a","$b"d "$MyFile"
  #insert the contents of this file after the structured body line
  sed -in '/MeasuresSection/r MeasuresAndReportingParametersWithVariables.xml' "$MyFile"
  sed -in  s/\<MeasuresSection\\/\>// "$MyFile"
done


rm -rf /home/nancy/CCR-Template/QRDA/PAT*.xmln

NewFunction()
{
File="PAT_$1_QRDA_V1_0_0-11-04-2010_21.xml"
shift
while [ "0" != "$#" ]
do
echo "Now I am in the function"
echo "$File"
echo "$1"
sed -in "s/<!--@@@$1-Tpl@@@//" "$File"
sed -in "s/<!--@@@$1-Item@@@//" "$File"
sed -in "s/<!--@@@$1-Act@@@//" "$File"
sed -in "s/<!--@@@M-Set2011@@@//" "$File"
sed -in "s/@@@@$1-Tpl@@@@-->//" "$File"
sed -in "s/@@@@$1-Item@@@@-->//" "$File"
sed -in "s/@@@@$1-Act@@@@-->//" "$File"
sed -in "s/@@@@M-Set2011@@@@-->//" "$File"
sed -in "s/<!--@@@M-Param2011@@@//" "$File"
sed -in "s/@@@@M-Param2011@@@@//" "$File"

shift
done
}

while read Line ; 
do
echo "$Line"

NewFunction $Line
done < "MEASURES-BY-PATIENT.txt"

rm -rf /home/nancy/CCR-Template/QRDA/PAT*.xmln