program ideone;

{$MODE FPC}

uses
  SysUtils;

  procedure RLEEncodeString(const AInput: AnsiString; var AOutput: AnsiString);
  var
    pchrLetter, pchrToken, pchrLast: PAnsiChar;
  begin
    pchrLast := @AInput[Length(AInput) + 1];
    pchrToken := @AInput[1];

    while pchrToken < pchrLast do
    begin
      pchrLetter := pchrToken;

      repeat
        Inc(pchrToken);
      until pchrToken^ <> pchrLetter^;

      AOutput := AOutput + pchrLetter^ + IntToStr(pchrToken - pchrLetter);
    end
  end;

  procedure RLEDecodeString(const AInput: AnsiString; var AOutput: AnsiString);
  var
    pchrLetter, pchrCntBegin, pchrCntEnd, pchrLast: PAnsiChar;
    strCount: AnsiString;
  begin
    pchrLast := @AInput[Length(AInput) + 1];
    pchrLetter := @AInput[1];

    while pchrLetter < pchrLast do
    begin
      pchrCntBegin := pchrLetter + 1;
      pchrCntEnd := pchrCntBegin + 1;

      while pchrCntEnd^ in ['0' .. '9'] do
        Inc(pchrCntEnd);

      SetLength(strCount, pchrCntEnd - pchrCntBegin);
      Move(pchrCntBegin^, strCount[1], pchrCntEnd - pchrCntBegin);

      AOutput := AOutput + StringOfChar(pchrLetter^, StrToInt(strCount));
      pchrLetter := pchrCntEnd;
    end;
  end;

var
  strInput, strOutput: AnsiString;
begin
  { encoding }
  strInput := 'AAANNNNTTTKKKK';

  WriteLn('Input:  ', strInput);
  RLEEncodeString(strInput, strOutput);
  WriteLn('Output: ', strOutput);

  WriteLn;

  { swap values }
  strInput  := strOutput;
  strOutput := '';

  { decoding }
  WriteLn('Input:  ', strInput);
  RLEDecodeString(strInput, strOutput);
  WriteLn('Output: ', strOutput);

  ReadLn;
end.
