<?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">
  <text># 
# column names
format var</text>
  <for-each select="FIELD">
    <choose>
      <when test="(@datatype='char' or @datatype='unicodeChar' or @datatype='boolean')" >
        <text> </text>
        <value-of select="@name"/>
      </when>
      <when test="(not(@arraysize) or number(@arraysize)=1) and @datatype!='floatComplex' and @datatype!='doubleComplex'">
        <text> </text>
        <value-of select="@name"/>
      </when>
    </choose>
  </for-each>
  <text>
</text>

  <if test="FIELD[@ucd='RECORD']">
    <text>#
# the ID column
format id </text>
    <value-of select="FIELD[@ucd='RECORD']/@name"/>
    <text>
</text>
  </if>

  <text>#
# table data
</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')" >
        <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'">
        <value-of select="normalize-space(.)"/>
        <text> </text>
      </when>
<!--      <otherwise>
        <value-of select="translate(normalize-space(.),' ','_')"/>
        <text> </text>
      </otherwise>  -->
    </choose>
  </for-each>
  <text>
</text>
</template>

</xsl:stylesheet>

