<?xml version="1.0" encoding="utf-8"?>
<CheatTable CheatEngineTableVersion="45">
  <CheatEntries>
    <CheatEntry>
      <ID>1</ID>
      <Description>"Zwei: The Ilvard Insurrection - Smooth Edition by dRambone | v1.0"</Description>
      <LastState Value="" RealAddress="00000000"/>
      <Color>80CAE4</Color>
      <GroupHeader>1</GroupHeader>
    </CheatEntry>
    <CheatEntry>
      <ID>2</ID>
      <Description>"Press F1 to attach to game and open trainer"</Description>
      <LastState Value="" RealAddress="00000000"/>
      <Color>AFAFAF</Color>
      <GroupHeader>1</GroupHeader>
    </CheatEntry>
  </CheatEntries>
  <UserdefinedSymbols/>
  <LuaScript>-- Zwei: The Ilvard Insurrection / Smooth Edition by dRambone
local old=rawget(_G,'ZweiTrainer')
if old and not old.closed and not old.cleanup() then return end
local TRAINER_VERSION='v1.0'
local GAME='Zwei: The Ilvard Insurrection'
local BRAND=GAME..' - Smooth Edition by dRambone | '..TRAINER_VERSION
local MODULE='ZWEI2PDX9.exe'
local ROOT=[[F:\Modding-AI\Projects\Zwei\]]
local EXE=[[F:\STEAM\steamapps\common\Zwei II\ZWEI2PDX9.exe]]
local C={bg=0x202020,card=0x2C2C2C,gold=0x80CAE4,text=0xF0F0F0,muted=0xAFAFAF,off=0x777777,red=0x7777EE}
local titles={'Infinite Health','Infinite Mana','Infinite Items','XP Multiplier','Pet XP Multiplier','Money Multiplier','Combo Multiplier','Walkspeed Multiplier','Perfect Timing'}
local cheatGroups={1,2,3,4,5,6,7,8,10}
local descriptions={
 'Prevents health loss from enemy damage',
 'Keeps your mana from running out',
 'Prevents consumable items from decreasing',
 'Multiplies experience gained from food',
 'Multiplies experience earned by your pet',
 'Multiplies money pickups (not shop sales)',
 'Multiplies combo progression',
 'Adjusts character movement speed',
 'Every eligible attack counts as perfectly timed.'
}
local S={rows={},hotkeys={},held={},factors={},editors={},patches={},active={},fields={}}
_G.ZweiTrainer=S
for i=4,8 do S.factors[i]=1 end
local function fail(s) error(s,0) end
local function at(va) return S.base+va-0x400000 end
local function live()
 if not S.pid or getOpenedProcessID()~=S.pid or getOpenedProcessHandle()~=S.handle then return false end
 local present=false
 for id,name in pairs(getProcesslist()) do
  if tonumber(id)==S.pid and name:lower()==MODULE:lower() then present=true; break end
 end
 return present and getAddressSafe(MODULE)==S.base and readSmallInteger(S.base)==0x5A4D
end
local function needGame()
 if not live() then fail('Game process ended or CE target changed. Press F1 to attach.') end
 local mode=readInteger(at(0x036261c4)); local transition=readInteger(at(0x03626260))
 if mode==nil or mode==2 or transition==nil or transition~=0 then fail('Load a save and wait for the map transition to finish.') end
 local level=readInteger(at(0x035c68f4)); local hp=readInteger(at(0x035c6924))
 if not level or level&lt;1 or level&gt;50 or not hp or hp&lt;1 then fail('Load a living playable character first.') end
end
local function guarded(fn)
 if S.busy or S.closed then return false end
 S.busy=true; local ok,e=pcall(fn); S.busy=false
 if S.refresh then S.refresh() end
 if not ok then showMessage(tostring(e)) end
 return ok
end
local function bytes(s)
 local t={}; for b in s:gmatch('%x%x') do t[#t+1]=tonumber(b,16) end; return t
end
local function equal(a,b)
 if not a or not b or #a~=#b then return false end
 for i=1,#a do if a[i]~=b[i] then return false end end; return true
end
local function mod(va) return MODULE..'+'..string.format('%X',va-0x400000) end
local function patch(group,va,original,body,factor)
 local p={group=group,va=va,original=original,body=body,factor=factor,id=#S.patches+1}
 S.patches[#S.patches+1]=p; return p
end
patch(1,0x004e6238,'2B 94 24 E4 02 00 00',nil)
patch(2,0x004d9877,'69 43 08 90 24 00 00',
 'mov dword ptr ['..mod(0x035c6928)..'],#5000\nimul eax,[ebx+08],2490')
for _,va in ipairs({0x00504c54,0x00515740}) do patch(3,va,'FE 8B 00 95 5D 03',nil) end
for _,va in ipairs({0x00504e23,0x005053d8,0x00515914,0x00515ed8}) do patch(3,va,'FE 83 00 95 5D 03',nil) end
local function scaled(register,source)
 return 'sub esp,10\nmovdqu [esp],xmm0\ncvtsi2ss xmm0,'..source..'\nmulss xmm0,[FACTOR]\ncvttss2si '..register..',xmm0\nmovdqu xmm0,[esp]\nadd esp,10\n'
end
for _,v in ipairs({{0x005055eb,'03 96 E8 B9 F2 02','esi'},{0x005160ea,'03 97 E8 B9 F2 02','edi'}}) do
 patch(4,v[1],v[2],'push eax\nmov eax,['..v[3]..'+'..mod(0x02f2b9e8)..']\n'..scaled('eax','eax')..'add edx,eax\npop eax',true)
end
for _,v in ipairs({{0x0050539e,'8B 04 BD 30 60 62 03 83 C0 32','edi'},{0x00515e96,'8B 04 95 30 60 62 03 83 C0 32','edx'}}) do
 patch(5,v[1],v[2],'mov eax,['..v[3]..'*4+'..mod(0x03626030)..']\npush ecx\nmov ecx,#50\n'..scaled('ecx','ecx')..'add eax,ecx\npop ecx',true)
end
patch(5,0x004e0adc,'FF 04 85 30 60 62 03',
 'pushfd\npush ecx\nmov ecx,1\n'..scaled('ecx','ecx')..'add [eax*4+'..mod(0x03626030)..'],ecx\npop ecx\npopfd',true)
for _,va in ipairs({0x004dffc1,0x004e0b28}) do
 patch(6,va,'01 05 08 69 5C 03','push eax\n'..scaled('eax','eax')..'add ['..mod(0x035c6908)..'],eax\npop eax',true)
end
patch(8,0x004da266,'8B 85 7C E5 FF FF',
 'pushfd\npush eax\nmov eax,[ebx+08]\ntest eax,eax\njne speedDone\nsub esp,10\nmovdqu [esp],xmm0\nmovss xmm0,['..mod(0x034a229c)..']\nmulss xmm0,[FACTOR]\nmovss ['..mod(0x034a229c)..'],xmm0\nmovdqu xmm0,[esp]\nadd esp,10\nspeedDone:\npop eax\npopfd\nmov eax,[ebp-1A84]',true)

local attrPatch=patch(9,0x004cbcd9,'C7 05 C8 A6 5D 00 06 00 00 00',nil)
local attrs={
 {'Strength',0x035c68fc,0x036261e0,0x005ad6c8,0,"Overrides the character's strength"},
 {'Magic',0x035c690c,0x036261e4,0x005ad6c8,0,"Overrides the character's magic attribute"},
 {'Defense',0x035c6900,0x036261e8,0x005ad6cc,10,"Overrides the character's defense"}
}
S.statActive={false,false,false}
local function attrScript()
 local t={'[ENABLE]','assert('..mod(attrPatch.va)..','..attrPatch.original..')',
  'alloc(zwiAttrs,2048,'..mod(attrPatch.va)..')',
  'label(zwiAttrControl)','label(zwiAttrRecalculate)','label(attrBack)',
  'registersymbol(zwiAttrControl)','registersymbol(zwiAttrRecalculate)'}
 for i=1,3 do t[#t+1]='label(attrNext'..i..')' end
 t[#t+1]='zwiAttrs:\npushfd\npushad\nsub esp,8C'
 for r=0,7 do t[#t+1]=string.format('movdqu [esp+%X],xmm%d',r*16,r) end
 for i,a in ipairs(attrs) do
  local o=(i-1)*24
  t[#t+1]=string.format('mov eax,[%s]\nmov [zwiAttrControl+%X],eax',mod(a[3]),o+8)
  t[#t+1]=string.format('mov eax,[%s]\nmov [zwiAttrControl+%X],eax',mod(a[2]),o+12)
  t[#t+1]=string.format('cmp dword ptr [zwiAttrControl+%X],0\nje attrNext%d',o,i)
  t[#t+1]=string.format('mov eax,[zwiAttrControl+%X]\nmov [%s],eax',o+4,mod(a[3]))
  t[#t+1]=string.format('cvtsi2ss xmm0,eax\nmovss xmm1,[%s]\ncall %s\ncvttss2si eax,xmm0',mod(a[4]),mod(0x0055c390))
  if a[5]~=0 then t[#t+1]='add eax,#'..a[5] end
  t[#t+1]=string.format('mov [%s],eax\nattrNext%d:',mod(a[2]),i)
  t[#t+1]=string.format('mov eax,[%s]\nmov [zwiAttrControl+%X],eax',mod(a[3]),o+16)
  t[#t+1]=string.format('mov eax,[%s]\nmov [zwiAttrControl+%X],eax',mod(a[2]),o+20)
 end
 t[#t+1]='inc dword ptr [zwiAttrControl+48]'
 for r=0,7 do t[#t+1]=string.format('movdqu xmm%d,[esp+%X]',r,r*16) end
 t[#t+1]='add esp,8C\npopad\npopfd\nmov dword ptr ['..mod(0x005da6c8)..'],6\njmp attrBack'
 t[#t+1]='zwiAttrRecalculate:\ncall '..mod(0x004cba90)..'\nmov eax,1\nret'
 t[#t+1]='align 4\nzwiAttrControl:\ndd '..string.rep('0 ',19)
 t[#t+1]=mod(attrPatch.va)..':\njmp zwiAttrs\ndb 90 90 90 90 90\nattrBack:'
 t[#t+1]='[DISABLE]\n'..mod(attrPatch.va)..':\ndb '..attrPatch.original
 t[#t+1]='unregistersymbol(zwiAttrControl)\nunregistersymbol(zwiAttrRecalculate)\ndealloc(zwiAttrs)'
 return table.concat(t,'\n')..'\n'
end
attrPatch.customScript=attrScript()

patch(7,0x004cdae5,'8B 0D 04 63 62 03',
 'label(comboCarry)\nlabel(comboBody)\nlabel(comboDone)\n'..
 'jmp comboBody\nalign 4\ncomboCarry:\ndd (float)0\ncomboBody:\n'..
 'pushfd\npush edx\nmov ecx,['..mod(0x03626304)..']\n'..
 'cmp ecx,#999999\njl @f\ndec ecx\njmp comboDone\n@@:\n'..
 'test ecx,ecx\njne @f\nmov dword ptr [comboCarry],0\n@@:\n'..
 'sub esp,20\nmovdqu [esp],xmm0\nmovdqu [esp+10],xmm1\n'..
 'movss xmm0,[FACTOR]\naddss xmm0,[comboCarry]\ncvttss2si edx,xmm0\n'..
 'cvtsi2ss xmm1,edx\nsubss xmm0,xmm1\nmovss [comboCarry],xmm0\n'..
 'movdqu xmm1,[esp+10]\nmovdqu xmm0,[esp]\nadd esp,20\n'..
 'lea ecx,[ecx+edx-1]\ncmp ecx,#999998\njle comboDone\nmov ecx,#999998\n'..
 'comboDone:\npop edx\npopfd',true)

for _,v in ipairs({{0x004d4bf3,'83 F9 04'},{0x004d4c20,'83 F9 02'},
                   {0x004d87a7,'83 F9 04'},{0x004d87d4,'83 F9 02'}}) do
 local p=patch(10,v[1],v[2],nil)
 local site=mod(p.va)
 p.customScript='[ENABLE]\nassert('..site..','..p.original..')\n'..
  site..':\ndb 83 F9 13\n[DISABLE]\n'..site..':\ndb '..p.original..'\n'
end

local function script(p)
 if p.customScript then return p.customScript end
 local site=mod(p.va); local name='zwiCave'..p.id; local factor='zwiFactor'..p.id
 local n=#bytes(p.original)
 local enable='[ENABLE]\nassert('..site..','..p.original..')\n'
 local disable='[DISABLE]\n'..site..':\ndb '..p.original..'\n'
 if not p.body then
  return enable..site..':\ndb '..string.rep('90 ',n)..'\n'..disable
 end
 local b=p.body:gsub('FACTOR',factor)
 enable=enable..'alloc('..name..',1024,'..site..')\nlabel(back)\nlabel(speedDone)\n'
 if not b:find('speedDone:',1,true) then enable=enable:gsub('label%(speedDone%)\n','') end
 if p.factor then enable=enable..'label('..factor..')\nregistersymbol('..factor..')\n' end
 enable=enable..name..':\n'..b..'\njmp back\n'
 if p.factor then enable=enable..'align 4\n'..factor..':\ndd (float)'..tostring(S.factors[p.group])..'\n' end
 enable=enable..site..':\njmp '..name..'\n'..(n&gt;5 and ('db '..string.rep('90 ',n-5)..'\n') or '')..'back:\n'
 if p.factor then disable=disable..'unregistersymbol('..factor..')\n' end
 return enable..disable..'dealloc('..name..')\n'
end
local function checkPatch(p,on)
 local expected=on and bytes(p.original) or p.installed
 if not equal(readBytes(at(p.va),#bytes(p.original),true),expected) then
  fail(string.format('Unexpected bytes at %s. No overwrite performed.',mod(p.va)))
 end
end
local function apply(p,on)
 if on==(p.info~=nil) then return end
 if not live() then fail('Game context changed; patch operation stopped.') end
 checkPatch(p,on)
 if on then p.script=script(p) end
 local ok,info=autoAssemble(p.script,false,on and nil or p.info)
 if not ok then fail('Auto Assembler: '..tostring(info)) end
 p.info=on and info or nil
 if on then p.installed=readBytes(at(p.va),#bytes(p.original),true) end
end
function S.toggle(i)
 guarded(function()
  needGame()
  local on=not S.active[i]
  local group=cheatGroups[i]
  for _,p in ipairs(S.patches) do if p.group==group and (p.info~=nil)~=on then checkPatch(p,on) end end
  local done={}
  local ok,e=pcall(function()
   for _,p in ipairs(S.patches) do if p.group==group then apply(p,on); done[#done+1]=p end end
  end)
  if not ok then
   if on then for j=#done,1,-1 do pcall(apply,done[j],false) end end
   fail(e)
  end
  S.active[i]=on
 end)
end
function S.setFactor(i)
 guarded(function()
  local value=tonumber((S.fields[i].Text:gsub(',','.')))
  local limit=i==8 and 10 or 100
  if not value or value~=value or value&lt;1 or value&gt;limit then fail('Enter a number from 1 to '..limit..'.') end
  if S.active[i] then
   needGame()
   local addresses={}
   for _,p in ipairs(S.patches) do
    if p.group==i and p.info and p.factor then
     local a=getAddressSafe('zwiFactor'..p.id)
     if not a or not readFloat(a) then fail('Multiplier memory is unavailable.') end
     addresses[#addresses+1]={address=a,old=readFloat(a)}
    end
   end
   local done={}
   local ok,err=pcall(function()
    for _,a in ipairs(addresses) do
     done[#done+1]=a
     if not writeFloat(a.address,value) then fail('Could not update multiplier.') end
     local got=readFloat(a.address)
     if not got or math.abs(got-value)&gt;0.0001 then fail('Multiplier verification failed.') end
    end
   end)
   if not ok then
    local restored=true
    for _,a in ipairs(done) do if not writeFloat(a.address,a.old) then restored=false end end
    fail(tostring(err)..(restored and ' Previous factors restored.' or ' Factor rollback failed; disable this cheat.'))
   end
  end
  S.factors[i]=value; S.fields[i].Text=tostring(value)
 end)
end

local configPath=ROOT..'Zwei.hotkeys.cfg'
S.bindings={}; S.keyFields={}; S.generations={}
local function defaults()
 local t={}; for i=1,#titles do t[i]={0x70+i,0} end; return t
end
local function valid(b)
 if type(b)~='table' then return false end
 local k,m=b[1],b[2]
 return type(k)=='number' and type(m)=='number' and m&gt;=0 and m&lt;=7 and m%1==0
  and ((k&gt;=0x41 and k&lt;=0x5A) or (k&gt;=0x30 and k&lt;=0x39)
  or (k&gt;=0x60 and k&lt;=0x6F) or (k&gt;=0x71 and k&lt;=0x87)) and k%1==0
  and not (m&amp;4~=0 and k==0x73)
end
local function modifiers()
 return (isKeyPressed(0x11) and 1 or 0)+(isKeyPressed(0x10) and 2 or 0)+(isKeyPressed(0x12) and 4 or 0)
end
local function keyText(b)
 local k,m=b[1],b[2]; local s=''
 if m&amp;1~=0 then s=s..'Ctrl+' end
 if m&amp;2~=0 then s=s..'Shift+' end
 if m&amp;4~=0 then s=s..'Alt+' end
 if k&gt;=0x70 then return s..'F'..(k-0x6F) end
 if k&gt;=0x60 and k&lt;=0x69 then return s..'Num'..(k-0x60) end
 local names={[0x6A]='Num*',[0x6B]='Num+',[0x6C]='Separator',[0x6D]='Num-',[0x6E]='Num.',[0x6F]='Num/'}
 return s..(names[k] or string.char(k))
end
local function check(t)
 local seen={}
 for i=1,#titles do
  if not valid(t[i]) then return false end
  local id=t[i][1]..':'..t[i][2]
  if seen[id] then return false end; seen[id]=true
 end
 return true
end
local function saveBindings()
 local ok,e=pcall(function()
  local file,err=io.open(configPath,'w'); if not file then error(err) end
  local lines={'ZWEI-HOTKEYS-1'}
  for i,b in ipairs(S.bindings) do lines[#lines+1]=i..'='..b[1]..','..b[2] end
  local wrote,err=file:write(table.concat(lines,'\n')..'\n')
  local closed,cerr=file:close()
  if not wrote or not closed then error(err or cerr or 'Write failed') end
 end)
 if not ok then showMessage('Hotkeys remain active but could not be saved: '..tostring(e)) end
end
local function loadBindings()
 local file=io.open(configPath,'r'); if not file then return defaults() end
 local t={}; local header=file:read('*l'); local good=header=='ZWEI-HOTKEYS-1'
 for line in file:lines() do
  local i,k,m=line:match('^(%d+)=(%d+),(%d+)$'); i=tonumber(i)
  if not i or i&lt;1 or i&gt;#titles or t[i] then good=false
  else t[i]={tonumber(k),tonumber(m)} end
 end
 file:close()
 if good and not t[9] then
  local used={}
  for i=1,8 do
   if not valid(t[i]) then good=false; break end
   local id=t[i][1]..':'..t[i][2]
   if used[id] then good=false; break end
   used[id]=true
  end
  if good then
   for key=0x79,0x87 do
    if not used[key..':0'] then t[9]={key,0}; break end
   end
  end
 end
 if good and check(t) then return t end
 showMessage('Invalid Zwei hotkey configuration. Defaults restored.')
 return defaults()
end
local function updateFields()
 for i,field in ipairs(S.keyFields) do field.Caption=keyText(S.bindings[i]) end
end
local function textInputActive()
 if not S.form or not S.form.isForegroundWindow() then return false end
 for _,fields in ipairs({S.fields,S.statFields or {}}) do
  for _,field in pairs(fields) do if field.Enabled and field.Visible and field.focused() then return true end end
 end
 return false
end
local function hotkeyAction(key,action)
 if S.closed then return end
 local function dispatch()
  if S.closed then return end
  if S.held[key] then return end
  S.held[key]=true
  if S.capture or textInputActive() then return end
  action()
 end
 if inMainThread() then dispatch() else synchronize(dispatch) end
end
local function makeHotkey(i,b,generation)
 local keys={b[1]}
 if b[2]&amp;1~=0 then keys[#keys+1]=0x11 end
 if b[2]&amp;2~=0 then keys[#keys+1]=0x10 end
 if b[2]&amp;4~=0 then keys[#keys+1]=0x12 end
 local h=createHotkey(function()
  if S.closed or S.generations[i]~=generation then return end
  hotkeyAction(b[1],function()
   if S.generations[i]==generation and modifiers()==b[2] then S.toggle(i) end
  end)
 end,table.unpack(keys))
 if not h then error('Could not register hotkey') end
 h.DelayBetweenActivate=180; return h
end

local function replaceBindings(t)
 local fresh={}; local generations={}
 local ok,e=pcall(function()
  for i=1,#titles do
   generations[i]=(S.generations[i] or 0)+1
   fresh[i]=makeHotkey(i,t[i],generations[i])
  end
 end)
 if not ok then
  for _,h in ipairs(fresh) do h.destroy() end
  showMessage('Hotkey registration failed; previous bindings retained: '..tostring(e)); return false
 end
 local previous=S.hotkeys
 S.generations=generations; S.hotkeys=fresh; S.bindings=t
 for _,h in ipairs(previous) do h.destroy() end
 updateFields(); return true
end
function S.cancelCapture()
 if S.pending then S.held[S.pending[1]]=true end
 S.capture=nil; S.pending=nil
 if S.captureEdit then S.captureEdit.Visible=false end
 updateFields()
end
function S.beginCapture(i)
 S.cancelCapture(); S.capture=i
 S.keyFields[i].Caption='PRESS KEY'
 S.captureEdit.Text='PRESS KEY - Esc cancels'
 S.captureEdit.Visible=true; S.captureEdit.setFocus()
end
function S.captureDown(sender,key)
 if not S.capture then return 0 end
 if key==0x1B then S.cancelCapture(); return 0 end
 if key==0x10 or key==0x11 or key==0x12 or (key&gt;=0xA0 and key&lt;=0xA5) then return 0 end
 if S.pending then return 0 end
 if isKeyPressed(0x5B) or isKeyPressed(0x5C) then showMessage('Windows-key combinations are reserved by the system.'); return 0 end
 local b={key,modifiers()}
 if not valid(b) then showMessage('Use letters, digits, numpad or F2-F24. F1 is reserved.'); return 0 end
 for i,other in ipairs(S.bindings) do
  if i~=S.capture and other[1]==b[1] and other[2]==b[2] then
   showMessage('This hotkey is already assigned to '..titles[i]..'.'); return 0
  end
 end
 S.pending=b; S.captureEdit.Text=keyText(b)..' - release key'
 return 0
end
function S.captureUp(sender,key)
 if not S.capture or not S.pending or key~=S.pending[1] then return 0 end
 local t={}; for i,b in ipairs(S.bindings) do t[i]={b[1],b[2]} end
 t[S.capture]=S.pending
 if replaceBindings(t) then saveBindings() end
 S.cancelCapture(); return 0
end
function S.resetBindings()
 S.cancelCapture()
 if replaceBindings(defaults()) then saveBindings() end
end
S.bindings=loadBindings()



local function label(parent,text,x,y,w,h,size,color)
 local l=createLabel(parent); l.Parent=parent; l.AutoSize=false; l.Left=x; l.Top=y; l.Width=w; l.Height=h
 l.Caption=text; l.Font.Name='Segoe UI'; l.Font.Size=size; l.Font.Color=color; return l
end
local function panel(parent,text,x,y,w,h,action)
 local p=createPanel(parent); p.Parent=parent; p.Left=x; p.Top=y; p.Width=w; p.Height=h
 p.Caption=text; p.Color=C.card; p.BevelOuter='bvNone'; p.Font.Name='Segoe UI'; p.Font.Size=10; p.Font.Color=C.gold
 if action then p.Cursor=-21; p.OnClick=action end; return p
end
local function edit(parent,x,y,w,text,callback)
 local e=createEdit(parent); e.Parent=parent; e.Left=x; e.Top=y; e.Width=w; e.Height=28; e.Text=text
 e.Color=C.bg; e.Font.Name='Segoe UI'; e.Font.Size=11; e.Font.Color=C.gold
 e.OnKeyDown=function(sender,key)
  if key==13 then
   callback()
   if parent.canFocus() then parent.setFocus()
   elseif S.focusTarget and S.focusTarget.canFocus() then S.focusTarget.setFocus() end
   return 0
  end
  return key
 end
 return e
end
local function statControl()
 local a=attrPatch.info and getAddressSafe('zwiAttrControl')
 if not a then fail('Attribute override control is unavailable.') end
 return a
end
local function statWrite(address,value)
 if not live() then fail('Game context changed; no attribute write performed.') end
 if not writeInteger(address,value) or readInteger(address)~=value then fail('Attribute control write/readback failed.') end
end
local function recalculateStats()
 if S.statCallUncertain then fail('Previous attribute call did not finish reliably. Restart the game before removing the attribute hook.') end
 if not live() then fail('Game context changed; recalculation stopped.') end
 checkPatch(attrPatch,false)
 local control=statControl(); local before=readInteger(control+72)
 local entry=getAddressSafe('zwiAttrRecalculate')
 if not entry or before==nil then fail('Cannot read attribute recalculation control.') end
 local ok,result=pcall(executeCodeEx,0,2000,entry)
 if not ok or result~=1 then
  S.statCallUncertain=true
  if live() then for i=0,2 do pcall(statWrite,control+i*24,0) end end
  fail('Attribute recalculation did not return its completion token. Overrides disabled; keep the hook allocated until the game exits. '..tostring(result))
 end
 if not live() or readInteger(control+72)==before then fail('Attribute calculation completion could not be verified.') end
 for i,a in ipairs(attrs) do
  local o=(i-1)*24; local enabled=readInteger(control+o)==1
  local display=readInteger(at(a[3])); local combat=readInteger(at(a[2]))
  local expectedDisplay=readInteger(control+o+(enabled and 4 or 8))
  local expectedCombat=readInteger(control+o+(enabled and 20 or 12))
  if display~=expectedDisplay or combat~=expectedCombat or not combat or combat&lt;1 then
   fail('Attribute readback failed for '..a[1]..'. No gameplay success is claimed.')
  end
 end
end
function S.readStats(only)
 needGame()
 for i,a in ipairs(attrs) do
  if not only or only==i then
  local value=readInteger(at(a[3])); if not value then fail('Could not read '..a[1]) end
  S.statFields[i].Text=tostring(value)
  end
 end
end
function S.writeStat(i)
 guarded(function()
  needGame(); local v=tonumber(S.statFields[i].Text)
  if not v or v~=v or v%1~=0 or v&lt;1 or v&gt;999 then fail('Enter an integer from 1 to 999. Combat scaling follows the game formula.') end
  if S.statCallUncertain then fail('Restart the game after the incomplete attribute recalculation.') end
  if not attrPatch.info then apply(attrPatch,true) end
  local control=statControl(); local o=(i-1)*24
  statWrite(control+o+4,v)
  statWrite(control+o,1); S.statActive[i]=true
  recalculateStats(); S.readStats(i)
  S.statMessage=attrs[i][1]..' verified in memory: status '..v..', combat '..readInteger(at(attrs[i][2]))..'.'
 end)
end
function S.resetStat(i)
 guarded(function()
  needGame()
  if not attrPatch.info then S.statActive[i]=false; S.readStats(i); return end
  if S.statCallUncertain then fail('Restart the game after the incomplete attribute recalculation.') end
  statWrite(statControl()+(i-1)*24,0); S.statActive[i]=false
  recalculateStats(); S.readStats(i)
  S.statMessage=attrs[i][1]..' reset: natural values recalculated and read back.'
  local any=false; for _,on in ipairs(S.statActive) do any=any or on end
  if not any then apply(attrPatch,false) end
 end)
end
function S.resetAllStats()
 if not attrPatch.info then S.statActive={false,false,false}; return end
 if not live() then
  for id in pairs(getProcesslist()) do if tonumber(id)==S.pid then fail('Select the original game process before resetting attributes.') end end
  S.statActive={false,false,false}; return
 end
 if S.statCallUncertain then fail('Attribute call status is uncertain. Exit the game before cleanup.') end
 local control=statControl(); local any=false
 for i=0,2 do any=any or readInteger(control+i*24)~=0; statWrite(control+i*24,0) end
 S.statActive={false,false,false}
 if any then
  local mode=readInteger(at(0x036261c4)); local transition=readInteger(at(0x03626260))
  local level=readInteger(at(0x035c68f4)); local hp=readInteger(at(0x035c6924))
  if mode~=nil and mode~=2 and transition==0 and level and level&gt;=1 and level&lt;=50 and hp and hp&gt;0 then
   recalculateStats(); S.readStats()
  end
 end
 apply(attrPatch,false)
 S.statMessage='Attribute overrides OFF; regular game calculation restored.'
end

local function bitRead(id)
 local b=readBytes(at(0x035d9100)+math.floor(id/8),1)
 if b==nil then fail('Could not read Notes flags.') end
 return (b&gt;&gt;(id%8))&amp;1
end
local function noteValue(entry,kind)
 if kind=='monster' then return bitRead(0x9c4+entry.note) end
 local seen=bitRead(0x640+entry.id); local mask=0
 for j=0,2 do mask=mask|(bitRead(0x6a4+entry.id+j*100)&lt;&lt;j) end
 local levels={[0]=0,[1]=1,[3]=2,[7]=3}
 local v=levels[mask]
 return v or 0,mask,seen
end
local function entries(kind)
 needGame(); local out={}; local count=kind=='monster' and 380 or 100
 for slot=0,count-1 do
  local a=at(0x030c3a84)+slot*0x27c
  local id=readInteger(a); local category=readInteger(a+0x5c); local note=readInteger(a+0x68)
  if id==nil or category==nil or note==nil then fail('Notes records could not be read.') end
  local include=kind=='monster' and category==0 and note&gt;0 and note&lt;199
   or kind=='character' and category~=0 and note&gt;0 and id&gt;=0 and id&lt;100
  if include then
   local name=readString(a+4,48,false)
   if not name or name=='' then name='ID '..id end
   name=name:gsub('[\r\n]',' ')
   out[#out+1]={id=id,note=note,slot=slot,name=name}
  end
 end
 if #out==0 then fail('No loaded Notes records found. Load a save first.') end
 return out
end
local function snapshot(e,kind)
 local value,mask,seen=noteValue(e,kind)
 return {value=value,mask=mask,seen=seen}
end
local function sameNote(a,b)
 return a.value==b.value and a.mask==b.mask and a.seen==b.seen
end
function S.openNotes(kind)
 guarded(function()
  needGame()
  local d=S.editors[kind]
  if d then d.reload(); d.form.show(); d.form.bringToFront(); return end
  entries(kind) -- Validate loaded data before allocating the editor window.
  d={page=0,perPage=10}; S.editors[kind]=d
  local f=createForm(false); d.form=f; f.Caption=(kind=='monster' and 'Monster Notes' or 'Character Notes')..' | '..BRAND
  f.Color=C.bg; f.Font.Name='Segoe UI'; f.Position='poScreenCenter'; f.BorderStyle='bsSingle'; f.ClientWidth=600; f.ClientHeight=665
  f.OnClose=function() return caHide end
  label(f,kind=='monster' and 'MONSTER NOTES' or 'CHARACTER NOTES',25,20,550,37,23,C.gold).Font.Style='[fsBold]'
  label(f,'Smooth Edition by dRambone',27,62,540,25,11,C.text)
  label(f,'Choose values, then Save Changes. Reload discards edits.',27,95,550,25,10,C.muted)
  label(f,kind=='monster' and 'Monster' or 'Character',30,127,400,24,11,C.muted)
  label(f,kind=='monster' and 'Unlocked' or 'Info Level',465,127,110,24,11,C.muted)
  d.labels={}; d.combos={}
  for row=1,d.perPage do
   local index=row; local y=160+(row-1)*38
   d.labels[row]=label(f,'',30,y,420,30,11,C.text)
   local cb=createComboBox(f); cb.Parent=f; cb.Left=465; cb.Top=y; cb.Width=100; cb.Height=28
   cb.Style='csDropDownList'; cb.Color=C.card; cb.Font.Name='Segoe UI'; cb.Font.Size=11; cb.Font.Color=C.gold
   for v=0,(kind=='monster' and 1 or 3) do cb.Items.add(tostring(v)) end
   cb.OnChange=function()
    if d.loading then return end
    local e=d.data[d.page*d.perPage+index]
    if e then e.pending=cb.ItemIndex; e.dirty=true end
   end
   d.combos[row]=cb
  end
  function d.render()
   d.loading=true
   for row=1,d.perPage do
    local e=d.data[d.page*d.perPage+row]; d.labels[row].Visible=e~=nil; d.combos[row].Visible=e~=nil
    if e then
     local suffix=e.original.mask and not ({[0]=true,[1]=true,[3]=true,[7]=true})[e.original.mask] and ' [mixed flags]' or ''
     d.labels[row].Caption=string.format('%s [ID %d]%s',e.name,e.id,suffix)
     d.combos[row].ItemIndex=e.pending
    end
   end
   d.pageText.Caption=string.format('%d / %d   (%d entries)',d.page+1,math.ceil(#d.data/d.perPage),#d.data)
   d.loading=false
  end
  function d.reload()
   needGame(); d.data=entries(kind); d.pid=S.pid; d.handle=S.handle; d.level=readInteger(at(0x035c68f4))
   for _,e in ipairs(d.data) do e.original=snapshot(e,kind); e.pending=e.original.value; e.dirty=false end
   d.page=0; d.render()
  end
  d.pageText=label(f,'',180,551,250,24,10,C.muted); d.pageText.Alignment='taCenter'
  local function page(delta)
   d.page=math.max(0,math.min(math.ceil(#d.data/d.perPage)-1,d.page+delta)); d.render()
  end
  panel(f,'PREVIOUS',25,548,130,30,function() page(-1) end)
  panel(f,'NEXT',445,548,130,30,function() page(1) end)
  f.OnMouseWheel=function(sender,shift,wheelDelta,x,y) page(wheelDelta&gt;0 and -1 or 1); return true end
  panel(f,'Save Changes',25,599,200,36,function()
   guarded(function()
    needGame()
    if d.pid~=S.pid or d.handle~=S.handle then fail('Process changed. Reload this editor first.') end
    if d.level~=readInteger(at(0x035c68f4)) then fail('Character level changed. Reload before saving Notes.') end
    local changed={}; local writes={}
    local function stage(bit,value)
     local a=at(0x035d9100)+math.floor(bit/8); local mask=1&lt;&lt;(bit%8)
     local w=writes[a]
     if not w then
      local oldByte=readBytes(a,1); if oldByte==nil then fail('Could not read Notes byte.') end
      w={address=a,old=oldByte,new=oldByte,mask=0}; writes[a]=w
     end
     if (w.mask&amp;mask)~=0 and ((w.new&amp;mask)~=0)~=(value==1) then fail('Conflicting edits share a Notes flag. Reload and use matching values.') end
     w.mask=w.mask|mask
     w.new=(w.new&amp;(~mask&amp;255))|(value==1 and mask or 0)
    end
    for _,e in ipairs(d.data) do
     if e.dirty then
      if not sameNote(snapshot(e,kind),e.original) then fail('Notes changed in game. Reload before saving: '..e.name) end
      changed[#changed+1]=e
      if kind=='monster' then stage(0x9c4+e.note,e.pending)
      else
       stage(0x640+e.id,e.pending&gt;0 and 1 or 0)
       for j=0,2 do stage(0x6a4+e.id+j*100,e.pending&gt;j and 1 or 0) end
      end
     end
    end
    if #changed==0 then showMessage('No changes to save.'); return end
    local paused=false; local done={}
    local ok,err=pcall(function()
     pause(); paused=true
     for _,e in ipairs(changed) do if not sameNote(snapshot(e,kind),e.original) then fail('Notes changed before Save. Reload required.') end end
     for _,w in pairs(writes) do
      local current=readBytes(w.address,1); if current==nil then fail('Notes byte became unreadable.') end
      w.old=current; w.new=(current&amp;(~w.mask&amp;255))|(w.new&amp;w.mask)
      done[#done+1]=w
      if not writeBytes(w.address,w.new) then fail('Notes write failed.') end
      if readBytes(w.address,1)~=w.new then fail('Notes readback failed.') end
     end
     for _,e in ipairs(changed) do if noteValue(e,kind)~=e.pending then fail('Notes verification failed for '..e.name) end end
    end)
    local rollbackError=false
    if not ok and paused and live() then
     for j=#done,1,-1 do local w=done[j]; if not writeBytes(w.address,w.old) or readBytes(w.address,1)~=w.old then rollbackError=true end end
    end
    if paused then pcall(unpause) end
    if not ok then fail(tostring(err)..(rollbackError and ' Partial changes remain: rollback failed.' or ' Written bytes rolled back.')) end
    d.reload(); showMessage('Notes changes verified in game memory. Use the game save menu to keep them.')
   end)
  end)
  panel(f,'Reload',245,599,150,36,function() guarded(d.reload) end)
  panel(f,'Close',415,599,160,36,function() f.hide() end)
  local ok,err=pcall(d.reload)
  if not ok then f.destroy(); S.editors[kind]=nil; fail(err) end
  f.show()
 end)
end

function S.refresh()
 local connected=live()
 for i,row in ipairs(S.rows) do
  local any=false; for _,p in ipairs(S.patches) do if p.group==cheatGroups[i] and p.info then any=true end end
  row.Caption=any and (connected and 'ON' or 'LOST') or 'OFF'
  row.Font.Color=any and C.gold or C.off
 end
 if S.status then S.status.Caption=connected and (S.statMessage or 'Attached') or 'Press F1 to attach' end
end
function S.attach()
 guarded(function()
  if live() then S.form.show(); S.form.bringToFront(); S.readStats(); return end
  local pid; local list=getProcesslist()
  for id,name in pairs(list) do
   if name:lower()==MODULE:lower() then
    if pid then fail('Multiple game instances found. Keep one instance running.') end
    pid=tonumber(id)
   end
  end
  if not pid then fail('ZWEI2PDX9.exe is not running. Start the Steam game first.') end
  if S.pid then
   for id in pairs(list) do
    if tonumber(id)==S.pid then
     for _,p in ipairs(S.patches) do if p.info then fail('Original process still exists. Select it again in CE before cleanup.') end end
    end
   end
  end
  local found=false
  for _,m in pairs(enumModules(pid) or {}) do
   if tostring(m.Name):lower()==MODULE:lower() then
    local path=tostring(m.PathToFile)
    if path:gsub('/','\\'):lower()~=EXE:lower() then fail('Unexpected executable path: '..path) end
    local file,err=io.open(path,'rb'); if not file then fail('Cannot verify EXE: '..tostring(err)) end
    local data=file:read('*a'); file:close()
    if stringToMD5String(data):lower()~='594bda93d5da0821a7409acdadb59f5a' then fail('Unsupported EXE build. No patches installed.') end
    found=true
   end
  end
  if not found then fail('Could not verify the game module.') end
  openProcess(pid)
  if getOpenedProcessID()~=pid or targetIs64Bit() then fail('Attachment to the 32-bit game failed.') end
  for _,p in ipairs(S.patches) do p.info=nil; p.installed=nil end
 S.active={}; S.statActive={false,false,false}; S.statCallUncertain=nil; S.statMessage=nil
 S.pid=pid; S.handle=getOpenedProcessHandle(); S.base=getAddressSafe(MODULE)
  if not live() then fail('Process identity verification failed.') end
  S.form.show(); S.form.bringToFront()
  pcall(S.readStats)
 end)
end
function S.cleanup()
 if S.closed then return true end
 local ok,e=pcall(function()
  if S.pid and not live() then
   for id in pairs(getProcesslist()) do
    if tonumber(id)==S.pid then
     for _,p in ipairs(S.patches) do if p.info then fail('Select the original process in CE before cleanup.') end end
    end
   end
  end
  if live() then
   for _,p in ipairs(S.patches) do if p.info then checkPatch(p,false) end end
   S.resetAllStats()
   for i=#S.patches,1,-1 do if S.patches[i].info then apply(S.patches[i],false) end end
  end
 end)
 if not ok then showMessage('Cleanup blocked: '..tostring(e)); return false end
 S.cancelCapture(); S.closed=true
 if S.timer then S.timer.destroy() end
 for _,h in ipairs(S.hotkeys) do h.destroy() end
 if S.attachHotkey then S.attachHotkey.destroy() end
 for _,d in pairs(S.editors) do d.form.destroy() end
 if S.form then S.form.destroy() end
 if S.watermark then S.watermark.destroy() end
 _G.ZweiTrainer=nil; return true
end

local f=createForm(false); S.form=f; f.Caption=BRAND; f.Color=C.bg; f.Font.Name='Segoe UI'
f.ClientWidth=760; f.Position='poScreenCenter'; f.BorderStyle='bsSingle'
S.focusTarget=f
f.OnClose=function()
 if not guarded(S.resetAllStats) then return caNone end
 S.cancelCapture(); return caHide
end
f.OnDeactivate=function() if S.capture then S.cancelCapture() end end
label(f,'ZWEI: THE ILVARD INSURRECTION',25,20,710,37,23,C.gold).Font.Style='[fsBold]'
label(f,'Smooth Edition by dRambone',27,62,400,25,11,C.text)
label(f,TRAINER_VERSION,500,62,235,25,10,C.muted)
label(f,'Click a hotkey to reassign it.',27,94,650,22,10,C.muted)
local y=130
for i,title in ipairs(titles) do
 local index=i
 local card=panel(f,'',25,y,710,56)
 if i==1 then S.focusTarget=card end
 S.keyFields[i]=panel(card,'',8,9,135,32,function() S.beginCapture(index) end); S.keyFields[i].Color=C.bg
 label(card,title,155,3,290,27,12,C.text)
 label(card,descriptions[i],155,30,292,23,9,C.muted)
 S.rows[i]=panel(card,'OFF',455,9,95,32,function()
  S.toggle(index); if card.canFocus() then card.setFocus() end
 end); S.rows[i].Color=C.bg
 if i&gt;=4 and i&lt;=8 then S.fields[i]=edit(card,570,10,120,'1.0',function() S.setFactor(index) end) end
 y=y+61
end
label(f,'Enter confirms multiplier (1-100; speed 1-10).',27,y,710,22,9,C.muted)
local attrsTop=y+30
S.statFields={}
for i,a in ipairs(attrs) do
 local index=i
 local card=panel(f,'',25+(i-1)*240,attrsTop,230,148)
 label(card,a[1],12,6,206,26,12,C.text)
 label(card,a[6],12,35,206,32,9,C.muted).WordWrap=true
 S.statFields[i]=edit(card,45,73,140,'?',function() S.writeStat(index) end)
 panel(card,'Apply',14,110,96,30,function()
  S.writeStat(index); if card.canFocus() then card.setFocus() end
 end)
 panel(card,'Reset',120,110,96,30,function()
  S.resetStat(index); if card.canFocus() then card.setFocus() end
 end)
end
label(f,'Status values: 1-999. Apply / Enter enables override; Reset restores natural values.',27,attrsTop+156,710,22,9,C.muted)
local notesTop=attrsTop+184
panel(f,'Monster Notes',25,notesTop,345,38,function() S.openNotes('monster') end)
panel(f,'Character Notes',390,notesTop,345,38,function() S.openNotes('character') end)
local statusTop=notesTop+46
S.status=label(f,'Press F1 to attach',27,statusTop,710,36,9,C.muted); S.status.WordWrap=true
local resetTop=statusTop+42
panel(f,'RESET HOTKEYS',250,resetTop,260,30,S.resetBindings)
S.captureEdit=createEdit(f); S.captureEdit.Parent=f; S.captureEdit.Left=430; S.captureEdit.Top=94; S.captureEdit.Width=305
S.captureEdit.Color=C.card; S.captureEdit.Font.Name='Segoe UI'; S.captureEdit.Font.Size=10; S.captureEdit.Font.Color=C.gold
S.captureEdit.ReadOnly=true; S.captureEdit.Visible=false; S.captureEdit.OnKeyDown=S.captureDown; S.captureEdit.OnKeyUp=S.captureUp
local contentHeight=resetTop+50
function S.fitMainWindow()
 f.VertScrollBar.Position=0
 local chrome=math.max(0,f.Height-f.ClientHeight)
 local available=math.max(240,getWorkAreaHeight()-chrome-24)
 f.ClientHeight=math.min(contentHeight,available)
 f.VertScrollBar.Range=contentHeight
 f.VertScrollBar.Visible=contentHeight&gt;f.ClientHeight
 f.VertScrollBar.Tracking=true; f.HorzScrollBar.Visible=false
end
S.fitMainWindow()
f.OnShow=function()
 S.fitMainWindow(); f.centerScreen()
 if S.focusTarget.canFocus() then S.focusTarget.setFocus() end
end
local main=getMainForm(); S.watermark=panel(main,'',0,0,760,26); S.watermark.Align='alTop'; S.watermark.Color=C.bg
local wm=label(S.watermark,GAME..' | created by dRambone | '..TRAINER_VERSION,0,0,760,26,10,C.gold)
wm.Align='alClient'; wm.Alignment='taCenter'; wm.Layout='tlCenter'
if not replaceBindings(S.bindings) then S.cleanup(); return end
S.attachHotkey=createHotkey(function()
 hotkeyAction(0x70,function() if modifiers()==0 then S.attach() end end)
end,0x70)
S.attachHotkey.DelayBetweenActivate=180
S.timer=createTimer(nil,false); S.timer.Interval=100
S.timer.OnTimer=function()
 if S.closed or S.busy then return end
 for vk in pairs(S.held) do if not isKeyPressed(vk) then S.held[vk]=nil end end
end
S.timer.Enabled=true; S.refresh(); S.ready=true
</LuaScript>
</CheatTable>
