<?php
function getE($text){
	$pos1 = strpos($text,'#E')+2;
	$pos2 = strrpos($text,'#E')-2;
	$text = substr($text, $pos1, $pos2-$pos1 );
	return $text;	
}

function getQrcode($HOSTNUMBER) {
	$secret_key 	= "Trisensa_diagnostic_centre";
	$secret_iv 		= "Gleneagles_surabaya";
	$encrypt_method = "AES-256-CBC";
	$key 			= hash('sha256', $secret_key);
	$iv 			= substr(hash('sha256', $secret_iv), 0, 16);

	$encrypted = base64_encode(openssl_encrypt($HOSTNUMBER, $encrypt_method, $key, 0, $iv));
	$qrcode = 'trisensadc.co.id/qrcode/data_detail.php?no_reg='.$encrypted;
	return $qrcode;
}

function f_repl($text, $ntext, $pos) {
	if($pos != 0) {
		$len = strlen($ntext); 
		if(substr($text,$pos,1) == ' ' ) { $text = substr_replace( $text, $ntext, $pos, $len); }
	}
	return $text;
}

function getResult($conn, $ACCESSNUMBER, $eng) {
include("_inc.php");
$sql = "SELECT DC.FULLTEXT, DT.TESTCODE, T.VALIDATIONSTATUS, 
RESULT = CASE 
	WHEN T.RESTYPE=0 THEN 'Pending'
	WHEN T.RESTYPE=4 AND T.RESVALUE='' AND T.RESSTATUS=1 THEN '.' -- null -> .
	WHEN T.RESTYPE IN (7,15,4) THEN T.RESVALUE
	WHEN T.RESTYPE=9 THEN +'< '+T.RESVALUE
	WHEN T.RESTYPE=10 THEN +'> '+T.RESVALUE
	WHEN T.RESVALUE IS NULL THEN 
		CASE
		WHEN T.CODEDRESULTID IS NULL AND DT.TESTTYPE IN (4,5) THEN null
		WHEN T.CODEDRESULTID IS NULL THEN TC.COMMENTTEXT
		WHEN T.CODEDRESULTID IS NOT NULL AND T.RESTYPE=6 AND SUBSTRING(DX.FULLTEXT,1,3) NOT LIKE '%#%' THEN DX.FULLTEXT
		END
	ELSE T.RESVALUE
END,
T.MINIMUM, T.MAXIMUM, 
DT.FULLTEXT,
DT.RESPRECISION,DT.RESPRECISION2, DT.OPERAND, DT.SOFTCONVERSION, DT.UNITS, DT.UNITS2, T.RESTYPE, VI.FULLTEXT,
case 
	when TC.COMMENTTEXT is null then DX2.FULLTEXT
	else TC.COMMENTTEXT
end, T.RERUN
FROM TESTS T 
JOIN DICT_TESTS DT ON DT.TESTID=T.TESTID
LEFT JOIN DICT_TEXTS DX ON DX.TEXTID=T.CODEDRESULTID
LEFT JOIN TESTS_COMMENTS TC ON TC.REQTESTID=T.REQTESTID
LEFT JOIN DICT_TEXTS DX2 ON DX2.TEXTID=TC.COMMENTCODEDID
LEFT JOIN REQUESTS R ON R.REQUESTID=T.REQUESTID
LEFT JOIN DICT_CHAPTERS DC ON DC.CHAPID=T.CHAPID
LEFT JOIN GDC_CMOD.dbo.V_INTER2 VI ON VI.ATR_ACCESSNUMBER=R.ACCESSNUMBER AND DT.TESTCODE=VI.ATR_TESTCODE
WHERE R.ACCESSNUMBER='$ACCESSNUMBER' AND T.NOTPRINTABLE IS NULL AND DT.TESTCODE<>'STATS' AND ISNUMERIC(DT.TESTCODE)=0
ORDER BY T.TESTORDER";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
$CHAP = "";
$i = 0;
$page = 1;
$line = 0;
$lpp = 37; // line per page
$done[1]= "";
$nline = 0;
$RERUN=1;


while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC)) {
	
	
	
	$CHAPTER = $row[0];
	$TESTCODE = $row[1];
	$VALIDATIONSTATUS = $row[2];
	$R1 = $row[3];
	if($R1=='****') {$R1='-';}
	$L1 = $row[4];
	$H1 = $row[5];
	$FULLTEXT = $row[6];
	$PRECISION1 = $row[7];
	$PRECISION2 = $row[8];
	$OPERAND = $row[9];// 3* 4/
	$SOFTCONVERSION =$row[10];
	$U1 = $row[11];
	$U2 = $row[12];
	$RESTYPE = $row[13];
	$I = $row[14];
	$RESCOM = $row[15];
	
	// Get ITEXT or ETEXT
	if($eng==1) { 
		$ICHAPTER = substr($CHAPTER, strpos($CHAPTER,'#E')+2, strrpos($CHAPTER,'#E')-strpos($CHAPTER,'#E')-2 );
		if($ICHAPTER != $CHAP) { 
			$raw[$i] =  "	<tr><td colspan='7'><pre>$ICHAPTER</pre></td> </tr>\r\n"; 
			$nline += 1;
		}
		$CHAP = $ICHAPTER;
		$ITEXT = substr($FULLTEXT, strpos($FULLTEXT,'#E')+2, strrpos($FULLTEXT,'#E')-strpos($FULLTEXT,'#E')-2 );		
	} else {
		$ICHAPTER = substr($CHAPTER,2, strrpos($CHAPTER,'#I')-2 );
		if($ICHAPTER != $CHAP) { 
			$raw[$i] =  "	<tr><td colspan='7'><pre>$ICHAPTER</pre></td> </tr>\r\n"; 
			$nline += 1;
		}
		$CHAP = $ICHAPTER;
		$ITEXT = substr($FULLTEXT,2, strrpos($FULLTEXT,'#I')-2 );
	}
	// GRP | ELE
	if($TESTCODE=='PCRN') { $raw[$i] .= "	<tr> <td></td> <td colspan='6'><br/><pre>$ITEXT</pre></td></tr>"; $done[$page] .= $raw[$i]; }
	elseif(!is_numeric($RESTYPE)) {
		// ch
		if( array_key_exists( $TESTCODE, $_chinese) ) { $ITEXT = rtrim($ITEXT)." <span class='textC'>".$_chinese[$TESTCODE].'</span>'; }
		if($ITEXT!='') {
			$ITEXT = "	<tr> <td colspan='7'><pre>$ITEXT</pre></td> </tr>\r\n";
			$nline += 1;
			$raw[$i] .= $ITEXT;
		}
	
		$RERUN = $row[16];
	} else {
		//flagging
		if( substr($R1,0,2)=='< ' && is_numeric(substr($R1,2,strlen($R1))) ) { $r1 = substr($R1,2,strlen($R1)); $r1-=1;}
		elseif( substr($R1,0,2)=='> ' && is_numeric(substr($R1,2,strlen($R1))) ) { $r1 = substr($R1,2,strlen($R1)); $r1+=1;}
		else {$r1 = $R1;}
		$F = "";
		if($TESTCODE != 'TROPI') {
			if($r1 < $L1 && is_numeric($r1) && is_numeric($L1)) {$F = "*L";}
			elseif($r1 > $H1 && is_numeric($r1) && is_numeric($H1)) {$F = "*H";}
		}
		// UNTUK LH
		if($TESTCODE == 'LH') {
			if($r1 < $L1 && is_numeric($r1) && is_numeric($L1)) {$F = "*L";}
			elseif($r1 > $H1 && is_numeric($r1) && is_numeric($H1)) {$F = "*H";}
			// else {$F = "*L";}
		}
		
		//get R2 L2 H2
		if($RESTYPE == 0) { $R2=""; $L1=""; $H1=""; $L2=""; $H2=""; }
		else {
			if(is_numeric($L1) && $PRECISION1 != 0 ) { $L1 = number_format($L1,$PRECISION1); } else { $L1 = number_format($L1); }
			if(is_numeric($H1) && $PRECISION1 != 0 ) { $H1 = number_format($H1,$PRECISION1); } else { $H1 = number_format($H1); }
			if( in_array($RESTYPE,[7,15,4]) && $OPERAND == 3 ) {
				if(is_numeric($R1)) { $R2 = NUMBER_FORMAT($R1 * $SOFTCONVERSION, $PRECISION2,'.',''); }
				else {$R2 = '';}
				if($L1 != 0) { $L2 = NUMBER_FORMAT($L1 * $SOFTCONVERSION, $PRECISION2); }
				else {$L2 = 0;}
				if(is_numeric($H1) && $H1 != 0) { $H2 = NUMBER_FORMAT($H1 * $SOFTCONVERSION, $PRECISION2); }
				else {$H2 = 0;}
			} elseif( in_array($RESTYPE,[7,15,4]) && $OPERAND == 4 ) {
				IF(is_numeric($R1)) { $R2 = NUMBER_FORMAT($R1 / $SOFTCONVERSION, $PRECISION2); }
				ELSE {$R2 = '';}
				IF(is_numeric($L1) && $L1 != 0) { $L2 = NUMBER_FORMAT($L1 / $SOFTCONVERSION, $PRECISION2); }
				ELSE {$L2 = 0;}
				IF(is_numeric($H1) && $H1 != 0) { $H2 = NUMBER_FORMAT($H1 / $SOFTCONVERSION, $PRECISION2); }
				ELSE {$H2 = 0;}
			} elseif ( in_array($RESTYPE,[9,10]) & $OPERAND == 3 ) { 
				$r21 = substr($R1, 0, 2);
				$r22 = substr($R1, 2, 10);
				$r22 = NUMBER_FORMAT($r22 * $SOFTCONVERSION, $PRECISION2,'.','');
				$R2 = $r21.$r22;
				if($L1 != 0) { $L2 = NUMBER_FORMAT($L1 * $SOFTCONVERSION, $PRECISION2); }
				else {$L2 = '';}
				if($H1 != 0) { $H2 = NUMBER_FORMAT($H1 * $SOFTCONVERSION, $PRECISION2); }
				else {$H2 = '';}
			} elseif ( in_array($RESTYPE,[9,10]) & $OPERAND == 4 ) {
				$r21 = substr($R1, 0, 2);
				$r22 = substr($R1, 2, 10);
				$r22 = NUMBER_FORMAT($r22 / $SOFTCONVERSION, $PRECISION2,'.','');
				$R2 = $r21.$r22;
				IF($L1 != 0) { $L2 = NUMBER_FORMAT($L1 / $SOFTCONVERSION, $PRECISION2); }
				ELSE {$L2 = '';}
				IF($H1 != 0) { $H2 = NUMBER_FORMAT($H1 / $SOFTCONVERSION, $PRECISION2); }
				ELSE {$H2 = '';}
			} else { $R2=$R1; $L2=$L1; $H2=$H1; }
		}
		if( ($L1 == 0) && ($H1 == 0) ) { $L1=''; $H1=''; $L2=''; $H2=''; }
		//precision1 
		if(is_numeric($R1) && is_numeric($PRECISION1)) { $R1 = NUMBER_FORMAT($R1,$PRECISION1,'.',','); }
		if(is_numeric($R2) && is_numeric($PRECISION2)) { $R2 = NUMBER_FORMAT($R2,$PRECISION2,'.',','); }
		
		// split in half - multi line
		// text | result
		
		$TEXT = explode("\r\n",$ITEXT);
		$test = array();
		$res = array();
		foreach($TEXT as $text) {
			$test[]= substr($text,0,33);
			$res[]= substr($text,33,strlen($text));
		}
		$space = ( strlen($test[0])-strlen(ltrim($test[0])) ) * 7;
		$test = rtrim(implode("\r\n",$test));
		$res = implode("\r\n",$res);
		
		// italic
		if( in_array( $TESTCODE, $_italic) ) { $test ="<i>$test</i>"; }
		// ch
		if( array_key_exists( $TESTCODE, $_chinese) ) { $test.=" <span class='textC'>".$_chinese[$TESTCODE].'</span>'; }
		//line count
		$tline = count( explode(PHP_EOL, $test) );
		$rline = count( explode(PHP_EOL, $res) );
		$r1line = count( explode(PHP_EOL, $R1) );
		if($rline < $r1line) { $rline = $r1line; }
		
		if ($test == ' Note') {
			$ITEXT = "	<tr> <td style='padding-left:".$space."px'><br/>$test</td> <td colspan='6'><br/><pre>$res            </pre></td> </tr>\r\n";	
		} elseif ( strlen($RESCOM) < 2 ) {
			//$ITEXT = "	<tr> <td style='padding-left:".$space."px'>$test</td> <td colspan='6'><pre>$res            </pre></td> </tr>\r\n";	
			$ITEXT = "	<tr> <td style='padding-left:".$space."px'>$test</td> <td colspan='6'><pre>$res  </pre></td> </tr>\r\n";	
		} else {
			$rline += count( explode(PHP_EOL, $RESCOM) );
			$res = rtrim($res);
			$ITEXT = "	<tr> <td style='padding-left:".$space."px'>$test</td> <td colspan='6'><pre>$res        \r\n$RESCOM</pre></td> </tr>\r\n ";
		}
		if($tline > $rline) { $nline += $tline; } else { $nline += $rline; }
		
		/*
		## replace {R1 {L1 {H1 {R2 {L2 {H2 {I ##
		GET STRING POS
		DELETE ALL STRING
		{R1,{R2,{I,{L1,{H1,{L2,{H2 // ORDER
		GET NEW STRING LENGTH
		*/
		// Get all string pos
		$posR1 = strpos($ITEXT, "{R1");
		$posR12 = strrpos($ITEXT, "{R1");
		$posR2 = strpos($ITEXT, "{R2");
		$posR22 = strrpos($ITEXT, "{R2");
		$posI1 = strpos($ITEXT, "{I");
		$posI2 = strrpos($ITEXT, "{I");
		
		$posL1 = strpos($ITEXT, "{L1");
		$posL12 = strrpos($ITEXT, "{L1");
		$posH1 = strpos($ITEXT, "{H1");
		$posH12 = strrpos($ITEXT, "{H1");
		$posL2 = strpos($ITEXT, "{L2");
		$posL22 = strrpos($ITEXT, "{L2");
		$posH2 = strpos($ITEXT, "{H2");
		$posH22 = strrpos($ITEXT, "{H2");
		$posU1 = strpos($ITEXT, "{U1");
		//all using U2
		//if($posU1 == 0 ) { $posU1 = strrpos($ITEXT, "{U2"); $U1 = $U2; }
		$posU2 = strpos($ITEXT, "{U2");
		#echo "<pre>$ITEXT</pre>\r\n";
		// Delete all string
		$ITEXT = str_replace( "{R1", "   ", $ITEXT );
		$ITEXT = str_replace( "{R2", "   ", $ITEXT );
		$ITEXT = str_replace( "{I", "  ", $ITEXT );
		$ITEXT = str_replace( "{L1", "   ", $ITEXT );
		$ITEXT = str_replace( "{H1", "   ", $ITEXT );
		$ITEXT = str_replace( "{L2", "   ", $ITEXT );
		$ITEXT = str_replace( "{H2", "   ", $ITEXT );
		$ITEXT = str_replace( "{U1", "   ", $ITEXT );
		$ITEXT = str_replace( "{U2", "   ", $ITEXT );
		// REPLACE
		if(in_array($RESTYPE, [4,6,7,9,10,15])) {
			$ITEXT = f_repl($ITEXT,$R1.' '.$F,$posR1);
			if($posR1 != $posR12) { $ITEXT = f_repl($ITEXT,$R1.' '.$F,$posR12); }
			$ITEXT = f_repl($ITEXT,$L1,$posL1);
			if($posL1 != $posL12) { $ITEXT = f_repl($ITEXT,$L1,$posL12); }
			$ITEXT = f_repl($ITEXT,$H1,$posH1);
			if($posH1 != $posH12) { $ITEXT = f_repl($ITEXT,$H1,$posH12); }
			if(isset($R2)) { 
				$ITEXT = f_repl($ITEXT,$R2.' '.$F,$posR2); 
				if($posR2 != $posR22) { $ITEXT = f_repl($ITEXT,$R2.' '.$F,$posR22); }
			}
			if(isset($L2)) { $ITEXT = f_repl($ITEXT,$L2,$posL2); }
			if($posL2 != $posL22) { $ITEXT = f_repl($ITEXT,$L2,$posL22); }
			if(isset($H2)) { $ITEXT = f_repl($ITEXT,$H2,$posH2); }
			if($posH2 != $posH22) { $ITEXT = f_repl($ITEXT,$H2,$posH22); }
			$ITEXT = f_repl($ITEXT,$I,$posI1);
			$ITEXT = f_repl($ITEXT,$I,$posI2);
			$ITEXT = f_repl($ITEXT,$U1,$posU1);
			$ITEXT = f_repl($ITEXT,$U2,$posU2);
		} elseif(in_array($RESTYPE,[2,0,5])) {
			if(strlen($RESCOM) < 2) {
				$ITEXT = substr($ITEXT, 0, $posR1);	$ITEXT .= $R1."</pre></td> </tr>"; 
			} else { 
				$ITEXT = substr($ITEXT, 0, $posR1);	$ITEXT .= "$R1 \r\n$RESCOM</pre></td> </tr>"; 
			}
		}
		// bold flag
		//$ITEXT = str_replace('*L', '<b>*L</b>', $ITEXT);
		//$ITEXT = str_replace('*H', '<b>*H</b>', $ITEXT);
		$raw[$i] .= $ITEXT;
		$line += $nline;
		
		if($TESTCODE != 'COVGG') {
			if($line > $lpp) {$page++; $done[$page] = ""; $line = $nline; }
		} else {
			if($line > $lpp-14) {$page++; $done[$page] = ""; $line = $nline; }
		}
		
		if($line > $lpp) {$page++; $done[$page] = ""; $line = $nline; }
		$done[$page] .= $raw[$i];
		$i++;
		$raw[$i] = "";
		$nline = 0;
	}	
}
return $done;
}

function getOthers($conn,$ACCESSNUMBER, $eng) {
	$sql = "select DT.FULLTEXT from TESTS T
		left join REQUESTS R on R.REQUESTID=T.REQUESTID
		left join DICT_TESTS DT on DT.TESTID=T.TESTID
		where R.ACCESSNUMBER='$ACCESSNUMBER' and ISNUMERIC(DT.TESTCODE)=1
		order by T.TESTORDER";
	$stmt = sqlsrv_query( $conn, $sql );
	if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
	$i = 1;
	$raw = "";
	while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
		$text = $row[0];
		if($eng==1) {
			$text = substr( $text , strpos($text,'#E')+2, strrpos($text,'#E')-strpos($text,'#E')-2 );
		} else {
			$text = substr( $text , strpos($text,'#I')+2, strrpos($text,'#I')-2 );
		}
		$text = str_replace( "{R1", "   ", $text );
		$text = str_replace( "{R2", "   ", $text );
		$text = str_replace( "{I", "  ", $text );
		$text = str_replace( "{L1", "   ", $text );
		$text = str_replace( "{H1", "   ", $text );
		$text = str_replace( "{L2", "   ", $text );
		$text = str_replace( "{H2", "   ", $text );
		$text = str_replace( "{U1", "   ", $text );
		$text = str_replace( "{U2", "   ", $text );
		$text = trim($text);
		$raw .= "$i. $text <br/>\r\n";
		$i++;
	}
	return $raw;
}

function getData($conn,$ACCESSNUMBER) {
$sql = "select R.EXTERNALORDERNUMBER, format(SR.COLLECTIONDATE,'dd/MM/yyyy'), P.NAME, right(P.PATNUMBER,16),
	rtrim(P.ADDRESS1+isnull(P.ADDRESS2,'')), P.TELEPHON, P.EMAIL,
	case
		when P.SEX=1 then 'Male'
		when P.SEX=2 then 'Female'
		else 'Unknown'
	end, 
	--FLOOR(DATEDIFF(DAY, P.BIRTHDATE, R.COLLECTIONDATE) / 365.25), 
	DATEDIFF(DAY, P.BIRTHDATE, R.COLLECTIONDATE) / 365.25+1, 
	MONTH(R.COLLECTIONDATE - DATEADD(year, DATEDIFF(year, P.BIRTHDATE, R.COLLECTIONDATE), P.BIRTHDATE) ) - 1,
	RO.COMMENTTEXT, P.STATE, P.CITY
from REQUESTS R 
left join SP_REQUESTS SR on SR.SP_ACCESSNUMBER=R.ACCESSNUMBER
left join PATIENTS P on P.PATID=R.PATID
left join REQUESTS_OCOM RO on RO.REQUESTID=R.REQUESTID
WHERE R.ACCESSNUMBER='$ACCESSNUMBER'";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC);
$regno = $row[0];
$reqdate = $row[1];
$pname = $row[2];
$pnum = $row[3];
$paddress = $row[4];
$pphone = $row[5];
$pemail = $row[6];
$psex = $row[7];
$pAge = $row[8];
$pAgeM = $row[9];
$rcomment = $row[10];
$pstate = $row[11];
$pcity = $row[12];
if($pstate == '') { $pstate = $pcity; }

//$sql = "select ODR_CRESULT_TO, ODR_CREFERENCENAME, ODR_CREFERENCEDOCNAME from GDC_CMOD.dbo.V_TDL_ORDER where ODR_CNOLAB='$regno'";
//$sql = "select ODR_CRESULT_TO, ODR_CREFERENCENAME, ODR_CREFERENCEDOCNAME from GLENEAGLES...TDL_ORDER where ODR_CNOLAB='$regno'";
$sql = "select ODR_CRESULT_TO, ODR_CREFERENCENAME, ODR_CREFERENCEDOCNAME from GDC_CMOD.dbo.TDL_ORDER where ODR_CNOLAB='$regno'";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC);
$sendto = $row[0];
$loc = $row[1];
$doc = $row[2];
if($loc == 'PT. BANGUN GUNUNG SARI (BGS)') { $loc = "PT. BANGUN GUNUNG SARI (BGS)"; }
elseif($loc == 'PT. PUTRA DUTA PEMBANGUNAN') { $loc = "PT. PUTRA DUTA PEMBANGUNAN"; }
elseif($loc == 'PT. BENSA ADHI CIPTA') { $loc = "-"; }
elseif($loc == 'PT. LIM SIANG HUAT BALINDO') { $loc = "-"; }
elseif($loc=='') { $loc = 'WALK IN'; }
if($doc=='') { $doc = $loc; }

// noreg, reqdate, access#, mr#, name,address, phone,email,sex,age,reff,doctor
$data ="<table class='info'>
	<tr style='border-bottom:solid 1px black'><th colspan='4'>LABORATORY REPORT</th></tr>
	<tr> <td>Reg#</td> <td>: $regno</td> <td>Date</td> <td><pre>: $reqdate  $sendto</pre></td></tr>
	<tr> <td>Lab#</td> <td colspan='3'>: $ACCESSNUMBER</td> </tr>
	<tr> <td>MR</td> <td colspan='3'>: $pnum</td> </tr>
	<tr> <td>Name</td> <td colspan='3'>: $pname</td> </tr>
	<tr> <td>Address</td> <td colspan='3'>: $paddress</td> </tr>
	<tr> <td>Phone/Email</td> <td colspan='3'>: $pphone / $pemail</td> </tr>
	<tr> <td>City</td> <td colspan='3'>: $pstate</td> </tr>
	<tr> <td>Sex</td> <td>: $psex</td> <td>Age</td> <td>: $pAge years, $pAgeM months</td></tr>
	<tr> <td>Reff</td> <td colspan='3'>: $loc</td></tr>
	<tr> <td>Doctor</td> <td colspan='3'>: $doc</td></tr>
</table>
";
return $data;
}

function getData2($conn,$ACCESSNUMBER) {
$sql = "select R.EXTERNALORDERNUMBER, format(SR.COLLECTIONDATE,'dd-MM-yyyy'), P.NAME, right(P.PATNUMBER,16),
	dmg.DMG_CADDRESS, P.TELEPHON, P.EMAIL,
	case
		when P.SEX=1 then 'Male'
		when P.SEX=2 then 'Female'
		else 'Unknown'
	end, 
	case when format(P.BIRTHDATE,'MMdd')=format(R.COLLECTIONDATE,'MMdd') then DATEDIFF(YEAR,P.BIRTHDATE, R.COLLECTIONDATE)
	else DATEDIFF(hour,P.BIRTHDATE, R.COLLECTIONDATE)/8766  end ,
	case when datepart(day,R.COLLECTIONDATE) >= datepart(day,P.BIRTHDATE) then datediff(month,P.BIRTHDATE, R.COLLECTIONDATE)%12
    else datediff(month, P.BIRTHDATE, dateadd(month,-1,R.COLLECTIONDATE))%12
    end,
	RO.COMMENTTEXT, dmg.DMG_CCITY, P.BIRTHDATE
from REQUESTS R 
left join SP_REQUESTS SR on SR.SP_ACCESSNUMBER=R.ACCESSNUMBER
left join PATIENTS P on P.PATID=R.PATID
left join REQUESTS_OCOM RO on RO.REQUESTID=R.REQUESTID
left join GDC_CMOD.dbo.TDL_DEMOGRAPHIC dmg on right(P.PATNUMBER,16)=dmg.DMG_CPATNUMBER collate Latin1_general_CS_AS
WHERE R.ACCESSNUMBER='$ACCESSNUMBER'";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC);
/*
$regno = $row[0];
$reqdate = $row[1];
$pname = $row[2];
$pnum = $row[3];
$paddress = $row[4];
$pphone = $row[5];
$pemail = $row[6];
$psex = $row[7];
$pAge = $row[8];
$pAgeM = $row[9];
$rcomment = $row[10];
$pcity = $row[11];

isset($row[0]) ? $row[0] : ''
*/
$regno = isset($row[0]) ? $row[0] : '';
$reqdate = isset($row[1]) ? $row[1] : '';
$pname = isset($row[2]) ? $row[2] : '';
$pnum = isset($row[3]) ? $row[3] : '';
$paddress = isset($row[4]) ? $row[4] : '';
$pphone = isset($row[5]) ? $row[5] : '';
$pemail = isset($row[6]) ? $row[6] : '';
$psex = isset($row[7]) ? $row[7] : '';
$pAge = isset($row[8]) ? $row[8] : '';
$pAgeM = isset($row[9]) ? $row[9] : '';
$rcomment = isset($row[10]) ? $row[10] : '';
$pcity = isset($row[11]) ? $row[11] : '';
$pdob = '' ;
if( isset($row[12]) ) 
	{ if($row[12]!= null ) { $pdob = date_format($row[12],'d-m-Y'); } }

//$sql = "select ODR_CRESULT_TO, ODR_CREFERENCENAME, ODR_CREFERENCEDOCNAME from GDC_CMOD.dbo.V_TDL_ORDER where ODR_CNOLAB='$regno'";
//$sql = "select ODR_CRESULT_TO, ODR_CREFERENCENAME, ODR_CREFERENCEDOCNAME from GLENEAGLES...TDL_ORDER where ODR_CNOLAB='$regno'";
$sql = "select ODR_CRESULT_TO, ODR_CREFERENCENAME, ODR_CREFERENCEDOCNAME from GDC_CMOD.dbo.TDL_ORDER where ODR_CNOLAB='$regno'";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC);
$sendto = isset($row[0]) ? $row[0] : '';
$loc = isset($row[1]) ? $row[1]: '';
$doc = isset($row[2]) ? $row[2]: '';

if($loc == 'PT. BANGUN GUNUNG SARI (BGS)') { $loc = "PT. BANGUN GUNUNG SARI (BGS"; }
elseif($loc == 'PT. PUTRA DUTA PEMBANGUNAN') { $loc = "PT. PUTRA DUTA PEMBANGUNAN"; }
elseif($loc == 'PT. BENSA ADHI CIPTA') { $loc = "-"; }
elseif($loc == 'PT. LIM SIANG HUAT BALINDO') { $loc = "-"; }
elseif($loc=='') { $loc = 'WALK IN'; }
if($doc=='') { $doc = $loc; }

// noreg, reqdate, access#, mr#, name,address, phone,email,sex,age,reff,doctor
$data ="<table class='info'>
	<tr style='border-bottom:solid 1px black'><th colspan='5'>CLINICAL LABORATORY</th></tr>
	<tr> <td>Reg#</td> <td>:</td> <td>$regno</td> <td>Date</td> <td><pre>: $reqdate  $sendto</pre></td></tr>
	<tr> <td>Lab#</td> <td>:</td> <td>$ACCESSNUMBER</td> <td>DoB</td> <td>: $pdob (D-M-Y)</td> </tr>
	<tr> <td>MR</td> <td>:</td> <td>$pnum</td> <td>Age</td> <td>: $pAge years, $pAgeM months</td> </tr>
	<tr> <td>Name</td> <td>:</td> <td colspan='3'>$pname</td> </tr>
	<tr> <td>Address</td> <td>:</td> <td colspan='3'>$paddress</td> </tr>
	<tr> <td>Phone/Email</td> <td>:</td> <td colspan='3'>$pphone / $pemail</td> </tr>
	<tr> <td>City</td> <td>:</td> <td colspan='3'>$pcity</td> </tr>
	<tr> <td>Sex</td> <td>:</td> <td colspan='3'>$psex</td> </tr>
	<tr> <td>Reff</td> <td>:</td> <td colspan='3'>$loc</td></tr>
	<tr> <td>Doctor</td> <td>:</td> <td colspan='3'>$doc</td></tr>
</table>
";
return $data;
}

function getHost($conn,$ACCESSNUMBER) {
	$sql = "select EXTERNALORDERNUMBER from REQUESTS where ACCESSNUMBER='$ACCESSNUMBER'";
	$stmt = sqlsrv_query( $conn, $sql );
	if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
	$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC);
	$HOSTNUMBER = isset($row[0]) ? $row[0] : '';
	return $HOSTNUMBER;	
}

function getNotes($conn, $ACCESSNUMBER) {
	/*
	$sql = "select case 
	when l.LOCID='3741' then p.TELEPHON2
	else null
	end,
	ro.COMMENTTEXT from REQUESTS r
	left join REQUESTS_OCOM ro on r.REQUESTID=ro.REQUESTID
	left join LOCATIONS l on r.REQUESTID=l.REQUESTID
	left join PATIENTS p on p.PATID=r.PATID
	where r.ACCESSNUMBER='$ACCESSNUMBER'";
	$stmt = sqlsrv_query( $conn, $sql );
	if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
	$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC);
	$notes = '';
	if(isset($row[0])) { $notes .= $row[0]."<br/>"; }
	$notes .= $row[1];
	*/
	$sql = "select ro.COMMENTTEXT from REQUESTS r
		left join REQUESTS_OCOM ro on r.REQUESTID=ro.REQUESTID
		where r.ACCESSNUMBER='$ACCESSNUMBER'";
	$stmt = sqlsrv_query( $conn, $sql );
	if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
	$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC);
	$notes = isset($row[0]) ? $row[0] : '';
	return $notes;
}

function getStatus($conn, $ACCESSNUMBER) {
	/*
	$sql = "select 
	case
	when exists ( select 1 from GDC_CMOD.dbo.TDL_ORDER t left join SP_REQUESTS r on r.HOSTORDERNUMBER=t.ODR_CNOLAB collate Latin1_general_CS_AS 
		WHERE r.SP_ACCESSNUMBER='$ACCESSNUMBER' and t.ODR_ISPENDING=1 ) then 'PENDING'
	when exists ( 
		select 1 from TESTS t
		left join REQUESTS r on r.REQUESTID=t.REQUESTID
		where r.ACCESSNUMBER='$ACCESSNUMBER' and 
		( t.RESTYPE=0 OR t.RESSTATUS=0 OR Left(t.RESVALUE,7)='Pending' )
		and t.NOTPRINTABLE is null
	) then 'PENDING'
	else 'FINAL' 
	end";
	*/
	$sql = "select STATS from GDC_CMOD.dbo.V_DASHBOARD where SP_ACCESSNUMBER='$ACCESSNUMBER'";
	$stmt = sqlsrv_query( $conn, $sql );
	if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
	$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC);
	if(isset($row[0])) {
		$status = $row[0];
		if($status == 'Comp') { $status = 'FINAL'; }
		else { $status = 'PENDING'; }
	} else { $status = ''; }
	return $status;
}

function getCollData($conn,$ACCESSNUMBER) {
	$collData = "";
	$sql = "select distinct format(COLLECTIONDATE,'dd-MM-yyyy'), format(COLLECTIONDATE,'HH:mm'), x = stuff(
		(select ', ' + dst.SHORTTEXT from GDC_CMOD.dbo.TUBES t1
		left join glendb.dbo.DICT_SAMPLES_TYPES dst on t1.TUBENUMBER=dst.SAMPCODE
		where t1.ACCESSNUMBER=t.ACCESSNUMBER 
		and format(t1.COLLECTIONDATE,'dd-MM-yyyy HH:mm')=format(t.COLLECTIONDATE,'dd-MM-yyyy HH:mm')
		for xml path('')),
	1,1, '')
	from GDC_CMOD.dbo.TUBES t where t.ACCESSNUMBER='$ACCESSNUMBER' and STATUS=1";
	$stmt = sqlsrv_query( $conn, $sql );
	if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
	$date1 = '';
	while ( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
		if($date1 == $row[0]) {	$collData .= $row[1].$row[2].'. '; }
		else { $collData .= $row[0].' '.$row[1].$row[2].'. '; }
		$date1 = $row[0];
	}
	return $collData;
}

function getRecvData($conn,$ACCESSNUMBER) {
	$recvData = "";
	$sql = "select DS.SHORTTEXT, format(S.LABRECEPTIONDATE,'dd-MM-yyyy'), format(S.LABRECEPTIONDATE,'HH:mm') from SAMPLES S
		left join DICT_SAMPLES_TYPES DS on DS.SAMPCODE=LEFT(S.SAMPLENUMBER,3)
		left join SP_TUBES ST on ST.TUBENB=right(S.FULLSAMPLENUM,13)
		where S.FULLSAMPLENUM like '%$ACCESSNUMBER' and ST.TUBESTATUS=4
		order by S.LABRECEPTIONDATE";
	$stmt = sqlsrv_query( $conn, $sql );
	if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
	$date1 = '';
	while ( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC) ) {
		$x = $row[0];
		$date = $row[1];
		$time = $row[2];
		if( $date1 == $date ) {	
			if($time1==$time) { $recvData .= $x.'. '; }
			else { $recvData .= $time.' '.$x.'. '; }
		}
		else { $recvData .= $date.' '.$time.' '.$x.'. '; }
		$date1 = $date;
		$time1 = $time;
	}
	return $recvData;
}


function getValBy($conn,$ACCESSNUMBER) {
$sql = "SELECT top 1 a.INITUSER, max(STEPDATE) as STEPDATE
	FROM glendb.dbo.AUDIT_TRAIL a WHERE (a.LIS_SESSION='VAL' or (a.LIS_SESSION='ERM' and a.VALIDATION=5))
	and a.ATR_ACCESSNUMBER='$ACCESSNUMBER'
	GROUP BY a.INITUSER, a.STEPDATE
	order by a.STEPDATE desc";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC);
$valBy = isset($row[0]) ? $row[0] : '';
if( $valBy == '' || $valBy =='LIS' ) { $valBy = "AHT"; }
return $valBy;
}

function getVal1($conn,$ACCESSNUMBER) {
$sql = "SELECT top 1 a.INITUSER, max(STEPDATE) as STEPDATE
	FROM glendb.dbo.AUDIT_TRAIL a WHERE (a.LIS_SESSION='VAL' or (a.LIS_SESSION='ERM' and a.VALIDATION=5))
	and a.ATR_ACCESSNUMBER='$ACCESSNUMBER'
	GROUP BY a.INITUSER, a.STEPDATE
	order by a.STEPDATE desc";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
$row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC);
$valBy = isset($row[0]) ? $row[0] : '';
$valDate = isset($row[1]) ? $row[1] : '';
if( $valBy == '' || $valBy =='LIS' ) { $valBy = "SYSTEM"; }
$val = [ 'valBy'=>$valBy, 'valDate'=>$valDate ];
return $val;
}

function getNoSample($conn,$ACCESSNUMBER) {

$sql = "select DST.SHORTTEXT from SP_TUBES ST 
	LEFT JOIN DICT_SAMPLES_TYPES DST ON DST.SAMPCODE=ST.TUBETYPE
	where ST.SP_ACCESSNUMBER='$ACCESSNUMBER' AND ST.TUBESTATUS<>4";

/*
$sql = "select DS.SHORTTEXT from SP_TUBES T 
	left join DICT_SAMPLES_TYPES DS on T.SAMPLETYPE=DS.SAMPCODE
	where T.SP_ACCESSNUMBER='$ACCESSNUMBER'
	and T.SAMPLETYPE not in (
		select substring(S.SAMPLENUMBER,0,4) from SAMPLES S
		left join REQUESTS R on R.REQUESTID=S.REQUESTID
		where R.ACCESSNUMBER=T.SP_ACCESSNUMBER
	) AND T.SAMPLETYPE <> '900'";
*/
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
$noSample = '';
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC)) {
	$sample = $row[0];
	$noSample .= "<tr> <td>$sample</td> <td colspan='6'>No Sample</td> </tr>\r";
}
return $noSample;
}

function getResultDebug($conn, $ACCESSNUMBER, $eng) {
include("_inc.php");
$sql = "SELECT DC.FULLTEXT, DT.TESTCODE, T.VALIDATIONSTATUS, 
RESULT = CASE 
	WHEN T.RESTYPE=0 THEN 'Pending'
	WHEN T.RESTYPE=4 AND T.RESVALUE='' AND T.RESSTATUS=1 THEN '.' -- null -> .
	WHEN T.RESTYPE IN (7,15,4) THEN T.RESVALUE
	WHEN T.RESTYPE=9 THEN +'< '+T.RESVALUE
	WHEN T.RESTYPE=10 THEN +'> '+T.RESVALUE
	WHEN T.RESVALUE IS NULL THEN 
		CASE
		WHEN T.CODEDRESULTID IS NULL AND DT.TESTTYPE IN (4,5) THEN null
		WHEN T.CODEDRESULTID IS NULL THEN TC.COMMENTTEXT
		WHEN T.CODEDRESULTID IS NOT NULL AND T.RESTYPE=6 AND SUBSTRING(DX.FULLTEXT,1,3) NOT LIKE '%#%' THEN DX.FULLTEXT
		END
	ELSE T.RESVALUE
END,
T.MINIMUM, T.MAXIMUM, 
DT.FULLTEXT,
DT.RESPRECISION,DT.RESPRECISION2, DT.OPERAND, DT.SOFTCONVERSION, DT.UNITS, DT.UNITS2, T.RESTYPE, VI.FULLTEXT,
case 
	when TC.COMMENTTEXT is null then DX2.FULLTEXT
	else TC.COMMENTTEXT
end, T.RERUN
FROM TESTS T 
JOIN DICT_TESTS DT ON DT.TESTID=T.TESTID
LEFT JOIN DICT_TEXTS DX ON DX.TEXTID=T.CODEDRESULTID
LEFT JOIN TESTS_COMMENTS TC ON TC.REQTESTID=T.REQTESTID
LEFT JOIN DICT_TEXTS DX2 ON DX2.TEXTID=TC.COMMENTCODEDID
LEFT JOIN REQUESTS R ON R.REQUESTID=T.REQUESTID
LEFT JOIN DICT_CHAPTERS DC ON DC.CHAPID=T.CHAPID
LEFT JOIN GDC_CMOD.dbo.V_INTER2 VI ON VI.ATR_ACCESSNUMBER=R.ACCESSNUMBER AND DT.TESTCODE=VI.ATR_TESTCODE
WHERE R.ACCESSNUMBER='$ACCESSNUMBER' AND T.NOTPRINTABLE IS NULL AND DT.TESTCODE<>'STATS'
ORDER BY T.TESTORDER";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt == false) { die( print_r( sqlsrv_errors(), true) ); }
$CHAP = "";
$i = 0;
$page = 1;
$line = 0;
$lpp = 34; // line per page
$done[1]= "";
$nline = 0;
$RERUN=1;
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC)) {
	$CHAPTER = $row[0];
	$TESTCODE = $row[1];
	$VALIDATIONSTATUS = $row[2];
	$R1 = $row[3];
	if($R1=='****') {$R1='-';}
	$L1 = $row[4];
	$H1 = $row[5];
	$FULLTEXT = $row[6];
	$PRECISION1 = $row[7];
	$PRECISION2 = $row[8];
	$OPERAND = $row[9];// 3* 4/
	$SOFTCONVERSION =$row[10];
	$U1 = $row[11];
	$U2 = $row[12];
	$RESTYPE = $row[13];
	$I = $row[14];
	$RESCOM = $row[15];
	
	// Get ITEXT or ETEXT
	if($eng==1) { 
		$ICHAPTER = substr($CHAPTER, strpos($CHAPTER,'#E')+2, strrpos($CHAPTER,'#E')-strpos($CHAPTER,'#E')-2 );
		if($ICHAPTER != $CHAP) { 
			$raw[$i] =  "	<tr><td colspan='7'><pre>$ICHAPTER</pre></td> </tr>\r\n"; 
			$nline += 1;
		}
		$CHAP = $ICHAPTER;
		$ITEXT = substr($FULLTEXT, strpos($FULLTEXT,'#E')+2, strrpos($FULLTEXT,'#E')-strpos($FULLTEXT,'#E')-2 );		
	} else {
		$ICHAPTER = substr($CHAPTER,2, strrpos($CHAPTER,'#I')-2 );
		if($ICHAPTER != $CHAP) { 
			$raw[$i] =  "	<tr><td colspan='7'><pre>$ICHAPTER</pre></td> </tr>\r\n"; 
			$nline += 1;
		}
		$CHAP = $ICHAPTER;
		$ITEXT = substr($FULLTEXT,2, strrpos($FULLTEXT,'#I')-2 );
	}
	// GRP | ELE
	if($TESTCODE=='PCRN') { $raw[$i] .= "	<tr> <td></td> <td colspan='6'><br/><pre>$ITEXT</pre></td></tr>"; $done[$page] .= $raw[$i]; }
	elseif(!is_numeric($RESTYPE)) {
		// ch
		if( array_key_exists( $TESTCODE, $_chinese) ) { $ITEXT = rtrim($ITEXT)." <span class='textC'>".$_chinese[$TESTCODE].'</span>'; }
		if($ITEXT!='') {
			$ITEXT = "	<tr> <td colspan='7'><pre>$ITEXT</pre></td> </tr>\r\n";
			$nline += 1;
			$raw[$i] .= $ITEXT;
		}
	
		$RERUN = $row[16];
	} else {
		//flagging
		if( substr($R1,0,2)=='< ' && is_numeric(substr($R1,2,strlen($R1))) ) { $r1 = substr($R1,2,strlen($R1)); $r1-=1;}
		elseif( substr($R1,0,2)=='> ' && is_numeric(substr($R1,2,strlen($R1))) ) { $r1 = substr($R1,2,strlen($R1)); $r1+=1;}
		else {$r1 = $R1;}
		if($r1 < $L1 && is_numeric($r1) && is_numeric($L1)) {$F = "*L";}
		elseif($r1 > $H1 && is_numeric($r1) && is_numeric($H1)) {$F = "*H";}
		else {$F="";}
		//echo "$R1<br/>";
		
		//get R2 L2 H2
		if($RESTYPE == 0) { $R2=""; $L1=""; $H1=""; $L2=""; $H2=""; }
		else {
			if( in_array($RESTYPE,[7,15,4]) && $OPERAND == 3 ) {
				if(is_numeric($R1)) { $R2 = NUMBER_FORMAT($R1 * $SOFTCONVERSION, $PRECISION2,'.',''); }
				else {$R2 = 0;}
				if($L1 != 0) { $L2 = NUMBER_FORMAT($L1 * $SOFTCONVERSION, $PRECISION2); }
				else {$L2 = 0;}
				if($H1 != 0) { $H2 = NUMBER_FORMAT($H1 * $SOFTCONVERSION, $PRECISION2); }
				else {$H2 = 0;}
			} elseif( in_array($RESTYPE,[7,15,4]) && $OPERAND == 4 ) {
				IF(is_numeric($R1)) { $R2 = NUMBER_FORMAT($R1 / $SOFTCONVERSION, $PRECISION2); }
				ELSE {$R2 = 0;}
				IF($L1 != 0) { $L2 = NUMBER_FORMAT($L1 / $SOFTCONVERSION, $PRECISION2); }
				ELSE {$L2 = 0;}
				IF($H1 != 0) { $H2 = NUMBER_FORMAT($H1 / $SOFTCONVERSION, $PRECISION2); }
				ELSE {$H2 = 0;}
			} else { $R2=$R1; $L2=$L1; $H2=$H1; }
		}
		//precision1 
		if(is_numeric($R1) && is_numeric($PRECISION1)) { $R1 = NUMBER_FORMAT($R1,$PRECISION1,'.',''); }
		
		// split in half - multi line
		// text | result
		$TEXT = explode("\r\n",$ITEXT);
		$test = array();
		$res = array();
		foreach($TEXT as $text) {
			$test[]= substr($text,0,33);
			$res[]= substr($text,33,strlen($text));
		}
		$space = ( strlen($test[0])-strlen(ltrim($test[0])) ) * 7;
		$test = rtrim(implode("\r\n",$test));
		$res = implode("\r\n",$res);
		// italic
		if( in_array( $TESTCODE, $_italic) ) { $test ="<i>$test</i>"; }
		// ch
		if( array_key_exists( $TESTCODE, $_chinese) ) { $test.=" <span class='textC'>".$_chinese[$TESTCODE].'</span>'; }
		//line count
		$tline = count( explode(PHP_EOL, $test) );
		$rline = count( explode(PHP_EOL, $res) );
		$r1line = count( explode(PHP_EOL, $R1) );
		if($rline < $r1line) { $rline = $r1line; }
		
		if ($test == ' Note') {
			$ITEXT = "	<tr> <td style='padding-left:".$space."px'><br/>$test</td> <td colspan='6'><br/><pre>$res            </pre></td> </tr>\r\n";	
		} elseif ( strlen($RESCOM) < 2 ) {
			$ITEXT = "	<tr> <td style='padding-left:".$space."px'>$test</td> <td colspan='6'><pre>$res            </pre></td> </tr>\r\n";	
		} else {
			$rline += count( explode(PHP_EOL, $RESCOM) );
			$res = rtrim($res);
			$ITEXT = "	<tr> <td style='padding-left:".$space."px'>$test</td> <td colspan='6'><pre>$res            \r\n$RESCOM</pre></td> </tr>\r\n ";
		}
		if($tline > $rline) { $nline += $tline; } else { $nline += $rline; }
		
		/*
		## replace {R1 {L1 {H1 {R2 {L2 {H2 {I ##
		GET STRING POS
		DELETE ALL STRING
		{R1,{R2,{I,{L1,{H1,{L2,{H2 // ORDER
		GET NEW STRING LENGTH
		*/
		// Get all string pos
		$posR1 = strpos($ITEXT, "{R1");
		$posR12 = strrpos($ITEXT, "{R1");
		$posR2 = strpos($ITEXT, "{R2");
		$posR22 = strrpos($ITEXT, "{R2");
		$posI1 = strpos($ITEXT, "{I");
		$posI2 = strrpos($ITEXT, "{I");
		$posL1 = strpos($ITEXT, "{L1");
		$posH1 = strpos($ITEXT, "{H1");
		$posL2 = strpos($ITEXT, "{L2");
		$posH2 = strpos($ITEXT, "{H2");
		$posU1 = strpos($ITEXT, "{U1");
		$posU2 = strpos($ITEXT, "{U2");
		#echo "<pre>$ITEXT</pre>\r\n";
		// Delete all string
		$ITEXT = str_replace( "{R1", "   ", $ITEXT );
		$ITEXT = str_replace( "{R2", "   ", $ITEXT );
		$ITEXT = str_replace( "{I", "  ", $ITEXT );
		$ITEXT = str_replace( "{L1", "   ", $ITEXT );
		$ITEXT = str_replace( "{H1", "   ", $ITEXT );
		$ITEXT = str_replace( "{L2", "   ", $ITEXT );
		$ITEXT = str_replace( "{H2", "   ", $ITEXT );
		$ITEXT = str_replace( "{U1", "   ", $ITEXT );
		$ITEXT = str_replace( "{U2", "   ", $ITEXT );
		// REPLACE
		if(in_array($RESTYPE, [4,6,7,9,10,15])) {
			$ITEXT = f_repl($ITEXT,$R1.' '.$F,$posR1);
			if($posR1 != $posR12) { $ITEXT = f_repl($ITEXT,$R1.' '.$F,$posR12); }
			$ITEXT = f_repl($ITEXT,$L1,$posL1);
			$ITEXT = f_repl($ITEXT,$H1,$posH1);
			if(isset($R2)) { 
				$ITEXT = f_repl($ITEXT,$R2.' '.$F,$posR2); 
				if($posR2 != $posR22) { $ITEXT = f_repl($ITEXT,$R2.' '.$F,$posR22); }
			}
			if(isset($L2)) { $ITEXT = f_repl($ITEXT,$L2,$posL2); }
			if(isset($H2)) { $ITEXT = f_repl($ITEXT,$H2,$posH2); }
			$ITEXT = f_repl($ITEXT,$I,$posI1);
			$ITEXT = f_repl($ITEXT,$I,$posI2);
			$ITEXT = f_repl($ITEXT,$U1,$posU1);
			$ITEXT = f_repl($ITEXT,$U2,$posU2);
		} elseif(in_array($RESTYPE,[0,5])) {
			if(strlen($RESCOM) < 2) {
				$ITEXT = substr($ITEXT, 0, $posR1);	$ITEXT .= $R1."</pre></td> </tr>"; 
			} else { 
				$ITEXT = substr($ITEXT, 0, $posR1);	$ITEXT .= "$R1 \r\n$RESCOM</pre></td> </tr>"; 
			}
		}
		// bold flag
		//$ITEXT = str_replace('*L', '<b>*L</b>', $ITEXT);
		//$ITEXT = str_replace('*H', '<b>*H</b>', $ITEXT);
		$raw[$i] .= $ITEXT;
		$line += $nline;
		
		if($TESTCODE != 'COVGG') {
			if($line > $lpp) {$page++; $done[$page] = ""; $line = $nline; }
		} else {
			if($line > $lpp-14) {$page++; $done[$page] = ""; $line = $nline; }
		}
		
		if($line > $lpp) {$page++; $done[$page] = ""; $line = $nline; }
		$done[$page] .= $raw[$i];
		$i++;
		$raw[$i] = "";
		$nline = 0;
	}	
}
return $done;
}

?>