<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <!-- identity -->
  <xsl:template match="@*|node()">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
  </xsl:template>

  <!-- Special handling for programme -->
  <xsl:template match="programme">
    <xsl:copy>
      <xsl:apply-templates select="@*"/>

      <!-- Grab xmltv_ns once -->
      <xsl:variable name="raw"
        select="normalize-space(episode-num[@system='xmltv_ns'][1])"/>

      <xsl:variable name="season0"
        select="number(substring-before($raw, '.'))"/>

      <xsl:variable name="rest"
        select="substring-after($raw, '.')"/>

      <xsl:variable name="episode"
        select="number(normalize-space(substring-before($rest, '.')))"/>

      <xsl:variable name="season" select="$season0 + 1"/>

      <!-- zero pad -->
      <xsl:variable name="s2">
        <xsl:choose>
          <xsl:when test="$season &lt; 10">
            <xsl:value-of select="concat('0',$season)"/>
          </xsl:when>
          <xsl:otherwise>
            <xsl:value-of select="$season"/>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:variable>

      <xsl:variable name="e2">
        <xsl:choose>
          <xsl:when test="$episode &lt; 10">
            <xsl:value-of select="concat('0',$episode)"/>
          </xsl:when>
          <xsl:otherwise>
            <xsl:value-of select="$episode"/>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:variable>

      <xsl:variable name="onscreenValue"
        select="concat('S',$s2,'E',$e2)"/>

      <!-- Copy all children EXCEPT existing onscreen -->
      <xsl:apply-templates
        select="node()[not(self::episode-num[@system='onscreen'])]" />

      <!-- Add the onscreen one at the end -->
      <episode-num system="onscreen">
        <xsl:value-of select="$onscreenValue"/>
      </episode-num>

    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>