Modern office phone systems can automatically forward incoming calls. For example, when an employee goes on vacation, they can arrange for every call that reaches their extension to be forwarded to a colleague. This problem simulates how such a system keeps track of call forwarding.
Every phone at the company has a four-digit extension. To set up call forwarding, an employee enters:
The rules are:
0000 and 9999 are reserved for special use and are never entered by an employee.0000 at midnight on New Year's Eve, so every time is an integer from 0000 to 8784 (which is $366 \times 24$). The system is completely reset at the start of each year.Employees always enter well-formed requests: they follow the format, no request runs past the end of the year, and no employee enters two requests for their own extension that overlap in time. As a result, at any moment each extension has at most one active forwarding rule.
Even so, forwarding can form a loop. For example, if A forwards to B, B forwards to C, and C forwards back to A, then a call to any of them would be forwarded forever. To handle this, whenever the forwarding chain followed from a called extension reaches an extension it has already passed through (that is, the chain enters a cycle), the call instead rings the special dead-end extension 9999.
The first line contains an integer $N$ ($1 \le N \le 10$): the number of independent call-forwarding systems to simulate.
Each system is described in two parts.
First come 0 to 100 forwarding requests, one per line, each in the form source time duration target (four four-digit numbers). They are listed in the order received. A line whose first field is 0000 ends this part.
Then come one or more calls, one per line, each in the form time extension, listed in non-decreasing order of time. Each such line means a call is placed at that time to that extension. A line whose first field is 9000 ends this part.
For each system, in order, print a line SYSTEM N, where N is the system's number (1, 2, ...). After that header, print one line for every call placed into that system, in input order, in the format:
AT tttt CALL TO eeee RINGS rrrr
where tttt is the call's time, eeee is the dialed extension, and rrrr is the extension the call finally rings. Starting from eeee, follow the active forwarding rules: if the chain reaches an extension with no active forwarding, that extension rings; if the chain enters a loop, the call rings 9999. All four values are printed as four digits.