program squares;

{VLADIMIR UFNAROVSCHI - REPUBLIC OF MOLDAVIA}

uses crt;

Const
   Down: Array['1'..'4'] of Char=('4','3','5','5');
   Up:   Array['1'..'4'] of Char=('5','5','2','1');
   Left: Array['1'..'4'] of Char=('5','1','4','5');
   Right:Array['1'..'4'] of Char=('2','5','5','3');

procedure Handle(var What:String; Comm:Char);
var
   i: Integer;
   Len, uk: Integer;
   ch: Char;
begin
  Len:=Length(What);
  uk:=Len;
  Case UpCase(Comm) of
 'D':begin
       Repeat
         ch:=Down[What[uk]];
         if ch='5'
           then begin What[uk]:=Up[What[uk]]; Dec(uk); end
           else begin What[uk]:=ch; uk:=-1; end;
       Until uk<=0
     end;
 'U':begin
       Repeat
         ch:=Up[What[uk]];
         if ch='5' then begin What[uk]:=Down[What[uk]]; Dec(uk); end
                   else begin What[uk]:=ch; uk:=-1; end;
       Until uk<=0
     end;
 'L':begin
       Repeat
         ch:=Left[What[uk]];
         if ch='5' then begin What[uk]:=Right[What[uk]]; Dec(uk); end
                   else begin What[uk]:=ch; uk:=-1; end;
       Until uk<=0
     end;
 'R':begin
       Repeat
         ch:=Right[What[uk]];
         if ch='5' then begin What[uk]:=Left[What[uk]]; Dec(uk); end
                   else begin What[uk]:=ch; uk:=-1; end;
       Until uk<=0
     end;
  end; {case}
  if uk=0 then What:='OUT OF THE BORDER.';
end;

procedure Main;
var
  i: Integer;
  What, Comm: String;
  f, f1: Text;
begin
  clrscr;
  Assign(f, 'square3.dat');
  Reset(f);
  Assign(f1, 'square.res');
  Rewrite(f1);
  While not EOF(f) do
    begin
      Readln(f, What);
      if What<>'' then
                    begin
                      Readln(f, Comm);
                      For i:=1 to Length(Comm) do
                        begin
                          Handle(What, Comm[i]);
                          if What='OUT OF THE BORDER.' then Break;
                        end;
                    end;
      Writeln(f1, What);
    end;
  Close(f);
  Close(f1);
end;

begin
  Main;
  writeln('Results are in square.res...');
  writeln;
  writeln('Press ENTER to continue...');
  readln
end.
