EnableExplicit

LibBuild_Include(AppBase)

Enumeration GetFileVersionField_Enum
  #GetFileVersionField_Comments
  #GetFileVersionField_CompanyName
  #GetFileVersionField_FileDesc
  #GetFileVersionField_FileVersion
  #GetFileVersionField_InternalName
  #GetFileVersionField_LegalCopyright
  #GetFileVersionField_LegalTrademarks
  #GetFileVersionField_OriginalFilename
  #GetFileVersionField_PrivateBuild
  #GetFileVersionField_ProductName
  #GetFileVersionField_ProductVersion
  #GetFileVersionField_SpecialBuild
  EndEnumeration

Procedure.s GetFileVersionField(FieldType.i, DefaultValue.s = "???")
  Define.s xResult
  Define.i xLong1.i
  Define.i xLong2.i
  Define.i xLong3.i
  Define *hMem
  Define.s xChar1.s
  Define.s FieldStr.s

  xLong1 = GetFileVersionInfoSize_(@LibBuild_BasePathRealExe, @xLong2)
  If xLong1
    *hMem = MemAlloc(xLong1)
    If *hMem
      xLong1 = GetFileVersionInfo_(LibBuild_BasePathRealExe, xLong2, xLong1, *hMem)
      If xLong1
        ;xChar1 = VerQueryValue(hMem, CStr(FieldType))
        Select FieldType
          Case #GetFileVersionField_Comments:         FieldStr = "Comments"
          Case #GetFileVersionField_CompanyName:      FieldStr = "CompanyName"
          Case #GetFileVersionField_FileDesc:         FieldStr = "FileDescription"
          Case #GetFileVersionField_FileVersion:      FieldStr = "FileVersion"
          Case #GetFileVersionField_InternalName:     FieldStr = "InternalName"
          Case #GetFileVersionField_LegalCopyright:   FieldStr = "LegalCopyright"
          Case #GetFileVersionField_LegalTrademarks:  FieldStr = "LegalTrademarks"
          Case #GetFileVersionField_OriginalFilename: FieldStr = "OriginalFilename"
          Case #GetFileVersionField_PrivateBuild:     FieldStr = "PrivateBuild"
          Case #GetFileVersionField_ProductName:      FieldStr = "ProductName"
          Case #GetFileVersionField_ProductVersion:   FieldStr = "ProductVersion"
          Case #GetFileVersionField_SpecialBuild:     FieldStr = "SpecialBuild"
          Default: xLong1 = 0
          EndSelect
        
        If xLong1
          xLong3 = VerQueryValue_(*hMem, @"\VarFileInfo\Translation", @xLong1, @xLong2)
          If xLong3 And xLong2 > 3
            xChar1 = Right("00000000" + LCase(Hex(PeekL(xLong1))), 8)
            FieldStr = "\StringFileInfo\" + Right(xChar1, 4) + Left(xChar1, 4) + "\" + FieldStr ;+ vbNullChar
            If VerQueryValue_(*hMem, @FieldStr, @xLong1, @xLong2)
              xResult = PeekS(xLong1, xLong2)
              EndIf
            EndIf
          EndIf
        EndIf
      MemFree(*hMem)
      EndIf
    EndIf
  If Not Len(xResult)
    xResult = DefaultValue
    EndIf
  ProcedureReturn xResult
  EndProcedure

; IDE Options = PureBasic 5.21 LTS (Windows - x86)
; Folding = -
; EnableUnicode
; EnableXP
; AddResource = ..\Calaym64\res\lng\en.rc