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

<!-- Pattern for the attribute values validation and ordering -->
<sch:pattern id="ValidateSortedAttributeValuesAgainstList" abstract="true" xmlns:sch="http://purl.oclc.org/dsdl/schematron">
    <sch:p id="ruleText">$rule</sch:p>
    <sch:p id="codeDesc">$code</sch:p>
    <sch:rule context="$context">
        <!-- Define variables -->             
        <sch:let name="dataFileElems" value="$curElems"/>
        <sch:let name="attrValues" value="$curAttr"/>
        <sch:let name="attrValueTokens" value="tokenize($attrValues,' ')"/>
        
        
        <!-- Get the position of each client node relative to its position in the master list.  If the node is not found, return a -1 -->
        <sch:let name="orderNums" value="
            for $token in $attrValueTokens return 
            if ($dataFileElems[matches($token,concat('^',text(),'$'))]) then 
            count(($dataFileElems[matches($token,concat('^',text(),'$'))])/preceding::*) + 1
            else -1"/>
        
        <!-- Create a sequence that returns a 0 if the previous sibling has a higher order number, else return a 1 -->            
        <sch:let name="sortedOrderNums" value="
            for $peice in distinct-values(for $token in $orderNums return index-of($orderNums,$token))
            return if($peice>1) then 
            if($orderNums[$peice] = $orderNums[$peice - 1]) then 
            if(compare($attrValueTokens[$peice - 1],$attrValueTokens[$peice]) = 1) then 0
            else 2
            else if($orderNums[$peice] > $orderNums[$peice - 1]) then 1
            else 0
            else 1
            "/>         
        <sch:let name="hasUnsorted" value="count(index-of($sortedOrderNums,0)) > 0" />
        <sch:let name="unsortedValues" value="
            if ($hasUnsorted) then
            distinct-values(
            for $token in index-of($sortedOrderNums,0) return
            $attrValueTokens[$token] 
            )
            else null
            "/>   
        
        <sch:assert test="not($hasUnsorted)" flag="$errFlag_AlphabeticalOrder"><sch:value-of select="$errMsg_AlphabeticalOrder"/>
            The following values are out of order [<sch:value-of
                select="$unsortedValues"/>] for [<sch:value-of select="$attrValueTokens"/>] </sch:assert>
    </sch:rule>
</sch:pattern>