<?xml version="1.0" encoding="UTF-8"?>

<!--
	Transform IANA's service/port number data into a usable services file.

	Author: Mike Gilbert <floppym@gentoo.org>
	This document is hereby placed in the public domain.

	Example usage:
	xsltproc services.xsl http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xml > services
-->

<xsl:transform version="1.0"
	xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
	xmlns:iana="http://www.iana.org/assignments">

	<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>

	<xsl:template match="iana:registry">
		<xsl:apply-templates select="iana:title|iana:updated|iana:note|iana:record"/>
	</xsl:template>

	<xsl:template match="iana:title">
		<xsl:call-template name="textblock">
			<xsl:with-param name="text" select="."/>
		</xsl:call-template>
	</xsl:template>

	<xsl:template match="iana:updated">
		<xsl:variable name="myval">
			<xsl:text>Updated: </xsl:text>
			<xsl:value-of select="."/>
		</xsl:variable>
		<xsl:call-template name="textblock">
			<xsl:with-param name="text" select="$myval"/>
		</xsl:call-template>
	</xsl:template>

	<xsl:template match="iana:xref[@type = 'rfc']">
		<xsl:text>RFC </xsl:text>
		<xsl:value-of select="substring(@data, 4)"/>
	</xsl:template>

	<xsl:template match="iana:note">
		<!-- Replace xrefs -->
		<xsl:variable name="myval">
			<xsl:apply-templates/>
		</xsl:variable>

		<!-- Create a block comment -->
		<xsl:call-template name="textblock">
			<xsl:with-param name="text" select="$myval"/>
		</xsl:call-template>
	</xsl:template>

	<xsl:template match="iana:record">
		<xsl:if test="iana:name and iana:number and iana:protocol">
			<xsl:value-of select="iana:name"/>
			<xsl:text>&#09;</xsl:text>
			<xsl:value-of select="iana:number"/>
			<xsl:text>/</xsl:text>
			<xsl:value-of select="iana:protocol"/>
			<xsl:text>&#09;# </xsl:text>
			<xsl:choose>
				<xsl:when test="contains(iana:description, '&#10;')">
					<xsl:value-of
						select="substring-before(iana:description, '&#10;')"/>
				</xsl:when>
				<xsl:otherwise>
					<xsl:value-of select="iana:description"/>
				</xsl:otherwise>
			</xsl:choose>
			<xsl:text>&#10;</xsl:text>
		</xsl:if>
	</xsl:template>

	<xsl:template name="textblock">
		<xsl:param name="text"/>
		<xsl:text># </xsl:text>
		<xsl:choose>
			<xsl:when test="contains($text, '&#10;')">
				<xsl:value-of select="substring-before($text, '&#10;')"/>
				<xsl:text>&#10;</xsl:text>
				<xsl:if test="string-length(substring-after($text, '&#10;')) > 0">
					<xsl:call-template name="textblock">
						<xsl:with-param name="text"
							select="substring-after($text, '&#10;')"/>
					</xsl:call-template>
				</xsl:if>
			</xsl:when>
			<xsl:otherwise>
				<xsl:value-of select="$text"/>
				<xsl:text>&#10;</xsl:text>
			</xsl:otherwise>
		</xsl:choose>
	</xsl:template>

</xsl:transform>
