' ############################################

Set GlobalFileSystem = CreateObject("Scripting.FileSystemObject")
Set GlobalShell = WScript.CreateObject("WScript.Shell")
Set GlobalUserEnvironment = GlobalShell.Environment("User")

WScript.Quit(Not Main)

' ############################################

Function Main
  Dim Success

  ' Initialize return value
  '
  Success = False

  ' Process arguments
  '
  If (WScript.Arguments.Count = 1) Then
    VarProjectFilePath = WScript.Arguments(0)

    ' Report directory of first document in project
    '
    VarDocumentDirectoryPath = GetDocumentDirectoryPath(VarProjectFilePath)
    If (Len(VarDocumentDirectoryPath) > 0) Then
      ' Set environment variable
      '
      Call WScript.Echo(VarDocumentDirectoryPath)

      ' Success!
      '
      Success = True
    End If
  End If

  ' Set return value
  '
  Main = Success
End Function


Function PathIsAbsolute(ParamPath)
  Dim VarPathIsAbsolute
  Dim VarDriveName

  ' Initialize return value
  '
  VarPathIsAbsolute = False

  ' Check for drive letter or UNC path
  '
  If (Len(ParamPath) >= 2) Then
    VarDriveName = GlobalFileSystem.GetDriveName(ParamPath)
    If (Len(VarDriveName) > 0) Then
      VarPathIsAbsolute = True
    ElseIf ((Mid(ParamPath, 1, 2) = "\\") Or _
            (Mid(ParamPath, 1, 2) = "//")) Then
      VarPathIsAbsolute = True
    End If
  End If

  PathIsAbsolute = VarPathIsAbsolute
End Function


Function GetDocumentDirectoryPath(ParamProjectFilePath)
  Dim VarDocumentDirectory
  Dim VarProject
  Dim VarDocument
  Dim VarDocumentPath
  Dim VarDocumentAbsolutePath
  Dim VarProjectDirectoryPath

  ' Initialize return value
  '
  VarDocumentDirectory = ""

  ' Load project
  '
  Set VarProject = CreateObject("Microsoft.XMLDOM")
  VarProject.async = "false"
  VarProject.load(ParamProjectFilePath)

  ' Find first document path
  '
  VarDocumentPath = ""
  For Each VarDocument In VarProject.selectNodes("/Project/Groups//Document[1]")
    For Each VarDocumentAttribute In VarDocument.attributes
      If (VarDocumentAttribute.name = "Path") Then
        VarDocumentPath = VarDocumentAttribute.value
      End If
    Next
  Next

  ' Report document directory
  '
  If (Len(VarDocumentPath) > 0) Then
    ' Determine absolute document directory path
    '
    If (PathIsAbsolute(VarDocumentPath)) Then
      VarDocumentAbsolutePath = VarDocumentPath
    Else
      VarProjectDirectoryPath = GlobalFileSystem.GetParentFolderName(ParamProjectFilePath)
      VarDocumentAbsolutePath = GlobalFileSystem.BuildPath(VarProjectDirectoryPath, VarDocumentPath)
    End If

    VarDocumentDirectory = GlobalFileSystem.GetParentFolderName(VarDocumentAbsolutePath)
  End If

  GetDocumentDirectoryPath = VarDocumentDirectory
End Function
