<?xml version='1.0' encoding='UTF-8'?>
<xsl:stylesheet xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<output method="text"/>

<template match="/">
  <apply-templates select="VOTABLE/RESOURCE/TABLE" />
</template>

<template match="TABLE">
  <for-each select="FIELD">
    <choose>
      <when test="(@datatype='char' or @datatype='unicodeChar' or @datatype='boolean') and position()!=last()" >
         <value-of select="@name"/>
	  <text>, </text>
      </when>
      <when test="((not(@arraysize) or number(@arraysize)=1) and @datatype!='floatComplex' and @datatype!='doubleComplex') and position()!=last()">      
	 <value-of select="@name"/>
	  <text>, </text>
      </when>
      <when test="(@datatype='char' or @datatype='unicodeChar' or @datatype='boolean') and position()=last()" >
         <value-of select="@name"/>
	  <text> </text>
      </when>
      <when test="((not(@arraysize) or number(@arraysize)=1) and @datatype!='floatComplex' and @datatype!='doubleComplex') and position()=last()">
        <value-of select="@name"/>
	  <text> </text>
      </when>

    </choose>
  </for-each>
  <text>
</text>

<apply-templates select="DATA/TABLEDATA/TR"/>
</template>

<template match="TR">
  <for-each select="TD">
    <variable name="col" select="position()"/>
    <choose>
      <when test="(../../../../FIELD[position()=$col]/@datatype='char' or ../../../../FIELD[position()=$col]/@datatype='unicodeChar' or ../../../../FIELD[position()=$col]/@datatype='boolean') and $col!=last()" >
        <value-of select="translate(normalize-space(.),' ','_')"/>
    <text>,</text>
      </when>
      <when test="((not(../../../../FIELD[position()=$col]/@arraysize) or number(../../../../FIELD[position()=$col]/@arraysize)=1) and ../../../../FIELD[position()=$col]/@datatype!='floatComplex' and ../../../../FIELD[position()=$col]/@datatype!='doubleComplex') and $col!=last()">
        <value-of select="normalize-space(.)"/>
        <text>, </text>
      </when>
     <when test="(../../../../FIELD[position()=$col]/@datatype='char' or ../../../../FIELD[position()=$col]/@datatype='unicodeChar' or ../../../../FIELD[position()=$col]/@datatype='boolean') and $col=last()" >
        <value-of select="translate(normalize-space(.),' ','_')"/>
    <text> 
</text>
      </when>
      <when test="((not(../../../../FIELD[position()=$col]/@arraysize) or number(../../../../FIELD[position()=$col]/@arraysize)=1) and ../../../../FIELD[position()=$col]/@datatype!='floatComplex' and ../../../../FIELD[position()=$col]/@datatype!='doubleComplex') and $col=last()">
        <value-of select="normalize-space(.)"/>
        <text> 
</text>
      </when>

    </choose>
  </for-each>
</template>

</xsl:stylesheet>
