#include "Include/close_trains.h"

// pattern closeTrains(start : Segment, end : Segment) {
// 	Train.location(_train, start);
// 	Segment.connectedTo(start, middle);
// 	Segment.connectedTo(middle, end);
// 	start != end;
// 	Segment.occupiedBy(end, _otherTrain);
// }

// Optimized and original queries are the same

void close_trains_matcher(ModelRoot *model, CloseTrainsFrame *frame,
                          int startOpIndex, CloseTrainsMatchSet *results) {
  int match_cntr = 0;

  int loop_bound0 = model->train_count;
  for (int i0 = 0; i0 < loop_bound0; i0++) {
    frame->t1 = model->trains[i0];
    frame->start = frame->t1->location;
    if (frame->start != 0) {
      int loop_bound1 = frame->start->connected_to_count;
      for (int i1 = 0; i1 < loop_bound1; i1++) {
        frame->middle = frame->start->connected_to[i1];
        int loop_bound2 = frame->middle->connected_to_count;
        for (int i2 = 0; i2 < loop_bound2; i2++) {
          frame->end = frame->middle->connected_to[i2];
          if (frame->start != frame->end) {
            frame->t2 = frame->end->train;
            if (frame->t2 != 0) {
              results->matches[match_cntr].start = frame->start;
              results->matches[match_cntr++].end = frame->end;
            }
          }
        }
      }
    }
  }

  results->size = match_cntr;
}
