VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
  Persistable = 0  'NotPersistable
  DataBindingBehavior = 0  'vbNone
  DataSourceBehavior  = 0  'vbNone
  MTSTransactionMode  = 0  'NotAnMTSObject
END
Attribute VB_Name = "CUnpacker"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = True
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Option Explicit

' IStream helpers

Private Declare Function FPC_IStream_AddRef Lib "f_in_box.dll" _
    (ByVal pStream As Long) As Long
    
Private Declare Function FPC_IStream_Release Lib "f_in_box.dll" _
    (ByVal pStream As Long) As Long
    
Private Declare Function FPC_IStream_Write Lib "f_in_box.dll" _
    (ByVal pStream As Long, _
    pData As Any, _
    ByVal nSize As Long, _
    ByRef nWritten As Long) As Long

Private bRunning As Boolean
Private oStream As Long ' IStream
Private hFile As Long

Public Property Get IsRunning() As Boolean
    IsRunning = bRunning
End Property

Public Sub Run(ByVal pStream As Long, ByVal lpszPath As String)
    If bRunning Then
        StopRunning
    End If
    
    hFile = CreateFile(lpszPath, GENERIC_READ, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0)
    If hFile <> INVALID_HANDLE_VALUE Then
        FPC_IStream_AddRef pStream
        oStream = pStream
        bRunning = True
    End If
End Sub

Public Sub Tick()
    Const nBufferSize As Long = 1024
    Dim pBuffer(nBufferSize) As Byte
    Dim dwNumberOfBytesRead As Long
    Dim dwNumberOfBytesWritten As Long
    Dim dwCounter As Long
    Dim bRes As Boolean
    
    While True
        bRes = ReadFile(hFile, pBuffer(0), nBufferSize, dwNumberOfBytesRead, 0)
        If Not bRes Or dwNumberOfBytesRead = 0 Then
            StopRunning
            Exit Sub
        Else
            ' Decrypt
            Dim I As Long
            For I = 0 To dwNumberOfBytesRead Step 1
                pBuffer(I) = pBuffer(I) Xor &H6
            Next
            'Write data to stream
            FPC_IStream_Write oStream, pBuffer(0), dwNumberOfBytesRead, dwNumberOfBytesWritten
        End If
    Wend
End Sub

Private Sub StopRunning()
    FPC_IStream_Release oStream
    CloseHandle hFile
    bRunning = False
End Sub

Private Sub Class_Terminate()
    If bRunning Then
        StopRunning
    End If
End Sub
