# How do I design a combinator circuit to keep track of a train's contents, even when not at the train stop?

I'm trying to design a combinator circuit that will output a signal with the train's content while a train is at the train stop (i.e. the same signal as the train stop's "Read train contents" mode), but when the train leaves, it should hold the signal at the content of the last train until the next train arrives.

In pseudo-code:

``````If T > 0                  # If a train is at the station
Output = Everything   # Output train contents
Else
Output = Output from previous tick
End
``````

So far, I've got this:

The first arithmetic combinator is set to `Each * -1 -> Each`, which is added to the signal from the train stop on the next tick to give the changes between each tick as a "delta-signal".

The decider combinator is set to `T >= 0 -> Everything` so that this "delta-signal" is ignored on the tick when the train leaves the station. (T > 0 indicates that a train is at the station, so "delta-T" will pulse negative as the train is leaving)

Finally, this is fed into a simple accumulating `Each + 0 -> Each` arithmetic combinator which also feeds into itself, acting as the memory cell of the system.

The result of this is that the memory cell updates continuously if I add or remove items from the train while it's at the station, and it correctly remembers the content as the train leaves.

However, I haven't been able to figure out how to reset it properly when the next train arrives, so currently, each train that arrives at the station adds to the current count rather than overwriting it.

I essentially need to ensure that on the tick when the train arrives, the current content of the memory cell is subtracted from the "delta signal", but I keep struggling to get the timing right while at the same time preventing the value of T from the memory cell (which I otherwise don't care about) from interfering without using a ton of combinators.

From left to right, the top two arithmetic combinators are set to `Each + 0 -> Each` and `T + 0 -> T`. This isolates the T signal on the right, and the left one is just there as a delay to keep the data + enable signal in sync with the isolated enable signal.
On the middle row, the left decider is set to `T > 0 -> Everything`, providing the update functionality, while the right decider is set to `T = 0 -> Everything` which enables the memory when the train is gone, so the combined output from this row is always either the train contents or the feedback value since the two conditions are disjoint.
The bottom row filters out the T signal using an arithmetic combinator `T * -1 -> T` together with another delay `Each + 0 -> Each`, and this filtered signal is fed back into the rightmost decider on the middle row. This prevents the feedback value of T from interfering with the enable logic on the middle row.