#include "MyTDT\Base64.bas"

function GetContentAsJS( sPath as string , sFile as string , sContent as string , bCreatePath as byte ) as string
  var sContentB64 = Base64_Encode( sContent )
  var sPathTree = iif(bCreatePath,"Module['FS_createPath'](""/"", """+sPath+""", true, true);","")
  return _
  "var Module = typeof Module != 'undefined' ? Module : {};" !"\n" _
  "Module['expectedDataFileDownloads'] ??= 0; Module['expectedDataFileDownloads']++;"  !"\n" _
  "(() => {" !"\n" _
  "  var isPthread = typeof ENVIRONMENT_IS_PTHREAD != 'undefined' && ENVIRONMENT_IS_PTHREAD;" !"\n" _
  "  var isWasmWorker = typeof ENVIRONMENT_IS_WASM_WORKER != 'undefined' && ENVIRONMENT_IS_WASM_WORKER;" !"\n" _
  "  if (isPthread || isWasmWorker) return;" !"\n" _
  "  function loadPackage(metadata) {" !"\n" _
  "    function runWithFS(Module) {"  !"\n" _
  "      function assert(check, msg) {" !"\n" _
  "        if (!check) throw msg + new error().stack;" !"\n" _
  "      }" !"\n"+sPathTree+!"\n" _
  "    var fileData0 = '"+sContentB64+"';" !"\n" _
  "    Module['FS_createDataFile']('/"+sPath+"', '"+sFile+"', atob(fileData0), true, true, true);" !"\n" _
  "    fileData0=''; Module['FS_Loaded'] += '"+sPath+sFile+";' }" !"\n" _
  "    if (Module['calledRun']) { runWithFS(Module); } else { (Module['preRun'] ??= []).push(runWithFS); }" !"\n" _  
  "  }" !"\n" _
  "  loadPackage({""files"": []});" !"\n" _
  "})();"
end function

var sFile = command(1), iBlockSz = cint(command(2))
print sFile
if iBlockSz <= 0 then iBlockSz = 512*1024 else iBlockSz *= 1024
if instr(sFile,".")=0 orelse open(sFile for binary access read as #1) then
  print "failed to open '"+sFile+"'" : sleep : system
end if

var sBlk = space(iBlockSz)

'var iExt = instrrev( sFile , ".")
'var sName = left(sFile,iExt-1) + ".", sExt = mid(sFile,iExt)
var sOutFile = sFile+".stream"
var iFilePos = len(sOutFile)
for N as long = 0 to len(sOutFile)-1
  select case sOutFile[N]
  case asc("\"): sOutFile[N] = asc("/") : iFilePos = N+1
  case asc("/"): iFilePos = N+1
  end select
next N

mkdir sOutFile

dim as ulong uRead,iNum=0
do
  get #1,,*cptr(ubyte ptr,strptr(sBlk)),iBlockSz,uRead  
  cptr(uinteger ptr,@sBlk)[1] = uRead
  open sOutFile & "\" & iNum for binary access write as #2
  put #2,,sBlk : close #2 
  open sOutFile & "\" & iNum & ".js" for binary access write as #2
  var sBlkJS = GetContentAsJS( mid(sOutFile,iFilePos+1) , "" & iNum  , sBlk , iNum=0 )
  put #2,,sBlkJS: close #2 
  iNum += 1  
loop until uRead < iBlockSz 

print "Done. splitted in " & iNum & " Blocks of " & iBlockSz/1024 & "kb"
sleep
  