unit Light2Heavy;

function AddKeywordIfMissing(kwda: IInterface; keywordFormID: Cardinal): Boolean;
var
  i: Integer;
  existing, newKeyword: IInterface;
begin
  Result := False;

  for i := 0 to ElementCount(kwda) - 1 do begin
    existing := LinksTo(ElementByIndex(kwda, i));

    if GetLoadOrderFormID(existing) = keywordFormID then
      Exit;
  end;

  newKeyword := RecordByFormID(FileByLoadOrder(0), keywordFormID, True);
  if Assigned(newKeyword) then begin
    ElementAssign(kwda, HighInteger, newKeyword, False);
    Result := True;
  end;
end;

function Process(e: IInterface): Integer;
var
  armorTypeStr: String;
  armorTypeVal: Integer;
  dnam, keywords, keyword, linked: IInterface;
  i,rating: Integer;
  formID: Cardinal;
begin
  if Signature(e) <> 'ARMO' then begin
    Exit;
  end;

  armorTypeStr := GetElementEditValues(e, 'BOD2\Armor Type');

  if armorTypeStr <> 'Light Armor' then
    Exit;

  SetElementEditValues(e, 'BOD2\Armor Type', 'Heavy Armor');
  keywords := ElementByPath(e, 'KWDA');
  if Assigned(keywords) then begin
    for i := ElementCount(keywords) - 1 downto 0 do begin
      keyword := ElementByIndex(keywords, i);
      linked := LinksTo(keyword);
      formID := GetLoadOrderFormID(linked);
      if formID = $0006BBD3 then begin
        RemoveElement(keywords, keyword);
      end;
    end;
    AddKeywordIfMissing(keywords, $0006BBD2)
  end;

  dnam := ElementByPath(e, 'DNAM');
  if Assigned(dnam) then begin
    rating := GetNativeValue(dnam);
    rating := rating * (4.0 / 3.0)/100;
    rating:=trunc(rating); 
    SetNativeValue(dnam,trunc(rating)*100);
  end;
  
end;

end.
