﻿
Param(
    [parameter(Mandatory=$true)][string]$InputFile,
    [parameter(Mandatory=$true)][string]$XsltFile,
    [parameter(Mandatory=$true)][string]$OutputFile,
    [parameter(Mandatory=$false)][string]$AxeCoreNet
)
    

# This try/finally block wraps the whole script so we can always properly dispose of objects.
#
try {


    # Need to know where our script is so we can use full path to all our dependent files.
    #
    $folderScript = Split-Path -Path $MyInvocation.MyCommand.Path -Parent

    # Also make sure all the current directory stuff resolves correctly.
    #
    [IO.Directory]::SetCurrentDirectory((Convert-Path (Get-Location -PSProvider FileSystem)))

    # Try to load up Axe because it is cool.
    #
    $boolRunningUnderAxe = $false
    if ( $AxeCoreNet ) {
        $axeAssembly = [Reflection.Assembly]::LoadFrom( $AxeCoreNet )
        if ( $axeAssembly ) {
            $axeSupport = [Microsoft.Assessments.Runtime.Support]::Initialize()
            if ( $axeSupport ) {

                $boolRunningUnderAxe = $axeSupport.EngineRunning

                $axeLogger = $axeSupport.CreateLogger()
            }
        }
    }

    # This function will write what is piped to it as a string to the default output
    # (usually the host/console) and also to the log file if running under axe.
    #
    function Log-Info {
        PROCESS {
            if ( $_ ) {
                "$_" | Out-Default
                if ( $axeLogger ) {
                    $axeLogger.LogMessage( "$_" )
                }
           }
        }
    }

    # This function will write what is piped to it as a string as an error
    # and also to the log file if running under axe.
    #
    function Log-Error([int32]$ErrorCode=1) {
        PROCESS {
            if ( $_ ) {
                "$_" | Write-Error
                if ( $axeLogger ) {
                    $axeLogger.LogError( $ErrorCode, "$_" )
                }
           }dx
        }
    }

    "-InputFile {$InputFile}" | Log-Info
    "-XsltFile {$XsltFile}" | Log-Info
    "-OutputFile {$OutputFile}" | Log-Info

    $InputFile = Convert-Path $InputFile
    $XsltFile = Convert-Path $XsltFile

    # Get an XSL Transform object
    #
    $xslt = New-Object System.Xml.Xsl.XslCompiledTransform
    $xsltSettings = New-Object System.Xml.Xsl.XsltSettings
    $xsltSettings.EnableDocumentFunction = $true;
   
    # Load xslt file
    #
    "Loading $XsltFile" | Log-Info
    $xslt.Load( $XsltFile, $xsltSettings, $null )
     
    # Do the transform
    #
    "Converting $InputFile" | Log-Info
    "Creating $OutputFile" | Log-Info
    $xslt.Transform( $InputFile, $OutputFile )


# This try/finally block wraps the whole script so we can always properly dispose of objects.
#
} finally {

    # We should always properly dispose of this guy.
    #
    if ( $axeSupport ) {
        $axeSupport.Dispose()
    }

}