###############################################################################
#
# Reads a file line by line with a random delay
# created: 06.07.2021 Michael Albert
#
###############################################################################

[CmdletBinding()]
Param(
  [Parameter(Mandatory=$true,Position=1)][alias("f")][string]$file="",
  [Parameter(Mandatory=$false,Position=2)][alias("j")][int]$startNumberOfJobs=256
)

if(!(Test-Path $file))
{
	write-warning "File $file not found!"
	exit 1
}
$oFile=Get-item $file
if($oFile -eq $null)
{
	write-host "File $file not found"
	exit 1
}
for($i=0;$i -le $startNumberOfJobs;$i++)
{
	write-host ([string]::Format("Start {0}", $oFile.FullName))
	Start-Job  -Name "Job $i" -InputObject $oFile.FullName -ScriptBlock {
		process{

			$sFullFilePath=$_
			$iReadBytes=8192
			$iReadPos=0
			[Char[]]$aBytes=new-object Char[] $iReadBytes
			do
			{
				$oBatchFile=[System.IO.File]::Open($sFullFilePath,[System.IO.FileMode]::Open,[System.IO.FileAccess]::Read,[System.IO.FileShare]::ReadWrite) 
				$iReedAtOffset=$oBatchFile.Seek($iReadPos,[System.IO.SeekOrigin]::Begin) 
				write-host "Offset:" $iReedAtOffset
				$oBinReader = new-object System.IO.BinaryReader($oBatchFile)
				$ReadBytes=$oBinReader.Read($aBytes, 0, $iReadBytes)
				$ReadString=[String]::Join("",$aBytes)
				$iNextLineEnd=($ReadString.IndexOf("`r`n"))
				$iReadPos+=$iNextLineEnd+2
				# Not aware of line > 8192 Char
				if($ReadBytes -lt $iReadBytes)
				{
					write-host "EOF"
				}
				elseif($iNextLineEnd -le -1)
				{
					write-host "Line longer then $iReadBytes detected. Exit"
					return
				}
				#write-host ($ReadString.SubString(0,$iNextLineEnd))
				Start-Sleep -Milliseconds (Get-Random -Maximum 100 -Minimum 10)
				$oBinReader.Close()
				$oBinReader.Dispose()
				$oBatchFile.Close()
				$oBatchFile.Dispose()
			}
			while($ReadBytes -eq $iReadBytes)
		}
	}
}	
