declare namespace cat = "http://www.iro.umontreal.ca/lapalme/wine-catalog";
declare default element namespace "http://www.w3.org/1999/xhtml";

declare variable $color external;

(: to produce legal and validable XHTML ... :)
declare option saxon:output "method=xml";
declare option saxon:output "doctype-public=-//W3C//DTD XHTML 1.0 Strict//EN";
declare option saxon:output "doctype-system=http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd";
declare option saxon:output "indent=yes";

(: using a direct element constructor, with an enclosed expression :)
declare function local:root($catalog){
    <html>
        <head><title>Wine Catalog</title></head>
        <body>
            {local:wine-catalog($catalog)}
        </body>   
    </html>
};

(:alternate definition of the function above using computed constructors :)
declare function local:root-bis($catalog){
    element html {
        element head {element title {"Wine Catalog"}},
        element body {local:wine-catalog($catalog)}
    }
};

declare function local:wine-catalog($catalog){
    element h1 {concat("Wine Catalog (",$color," only)")},
    element table {
        attribute border {1},
        element tr {
            for $t in ('Wine Name','Code','Color','Year','Price','ml','l')
                return element th{$t}},
        for $wine in $catalog/cat:wine
            where $wine/cat:properties/cat:color=$color
            return local:wine($wine) 
    }        
};

declare function local:wine($wine){
    <tr>{
        <td>{data($wine/@name)}</td>,
        <td>{data($wine/@code)}</td>,
        <td>{data($wine/cat:properties/cat:color)}</td>,
        <td align="right">{data($wine/cat:year)}</td>,
        (: format-number is not available in XQuery 1.0 !! :)
        <td align="right">{concat('$',$wine/cat:price)}</td>, 
        <td align="right">{local:toML($wine/@format)}</td>,
        <td align="right">{local:toL($wine/@format)}</td>
        }
    </tr>
};

declare function local:toML($fmt){
    if ($fmt='375ml') then '375'
    else if ($fmt='750ml') then '750'
    else if ($fmt='1l') then '1000'
    else if ($fmt='magnum') then '1500'
    else 'big'
};

declare function local:toL($fmt){
    let $ml := local:toML($fmt)
    return 
        if ($ml castable as xs:integer) 
           then number($ml) div 1000 
           else $ml
};

local:root(/cat:wine-catalog)