<?xml version="1.0"?> 
<xsl:stylesheet version="2.0" 
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xmlns:results="Results" xmlns:xs="http://www.w3.org/2001/XMLSchema" 
	xmlns:fn="http://www.w3.org/2005/xpath-functions"
	xmlns:map="map:java.util.Map" 
	xmlns:clinicaldata="Clinicaldata"
	exclude-result-prefixes="fn xs xsi xsl map results clinicaldata">
	<xsl:output method="text" encoding="UTF-8" omit-xml-declaration="no"/>
	
	<xsl:template match="/clinicaldata:ClinicalData">{"sites":
		[<xsl:for-each select="./patients/patient/genericObservations/genericObservation">
			<xsl:call-template name="genericObservationTemplate"/>
		</xsl:for-each>
		<xsl:if test="count(./patients/patient/genericObservations/genericObservation) > 0 and count(./errorSection) = 1">,</xsl:if>
		<xsl:if test="count(./errorSection) = 1">
			<xsl:call-template name="errorSectionTemplate"/>
		</xsl:if>]
		}
	</xsl:template>
			
	<xsl:template name="genericObservationTemplate">
		<xsl:value-of select="observationValue"/><xsl:if test="position() != last()">,</xsl:if>
	</xsl:template>
	
	<xsl:template name="errorSectionTemplate">{ "errorSection":{
			<xsl:if test="count(./errorSection/errors/error) &gt;= 1">"errors":[
				<xsl:for-each select="./errorSection/errors/error">{
					<xsl:call-template name="exceptionTemplate"/>}<xsl:if test="position() != last()">,</xsl:if>
				</xsl:for-each>]<xsl:if test="count(./errorSection/fatalErrors/fatalError) + count(./errorSection/warnings/warning) &gt; 0">,</xsl:if>
			</xsl:if>
			<xsl:if test="count(./errorSection/fatalErrors/fatalError) &gt;= 1">"fatalErrors":[
				<xsl:for-each select="./errorSection/fatalErrors/fatalError">{
					<xsl:call-template name="exceptionTemplate"/>}<xsl:if test="position() != last()">,</xsl:if>
				</xsl:for-each>]<xsl:if test="count(./errorSection/warnings/warning) &gt; 0">,</xsl:if>
			</xsl:if>
			<xsl:if test="count(./errorSection/warnings/warning) &gt;= 1">"warnings":[
				<xsl:for-each select="./errorSection/warnings/warning">{
					<xsl:call-template name="exceptionTemplate"/>}<xsl:if test="position() != last()">,</xsl:if>
				</xsl:for-each>]
			</xsl:if>
		}}
	</xsl:template>	
	
	<xsl:template name="exceptionTemplate">
		"exceptionMessage":"<xsl:value-of select="exceptionMessage"/>",
		"displayMessage":"<xsl:value-of select="displayMessage"/>",
		"exception":"<xsl:value-of select="exception"/>",
		"errorCode":"<xsl:value-of select="errorCode"/>",
		"errorId":"<xsl:value-of select="errorId"/>"
	</xsl:template>
	
</xsl:stylesheet>
