#include <SoftwareSerial.h>

// Definiáljuk a másik sorosportot (RX, TX)
SoftwareSerial mySerial(10, 11);

String gcodeLine = "";
float x = 0, y = 0, z = 0;

void setup() {
  Serial.begin(9600); // Alapértelmezett sorosport sebessége
  mySerial.begin(9600); // Másik sorosport sebessége
}

void loop() {
  while (Serial.available() > 0) {
    char c = Serial.read();
    if (c == '\n') {
      processGCode(gcodeLine);
      gcodeLine = "";
    } else {
      gcodeLine += c;
    }
  }
}

void processGCode(String line) {
  if (line.startsWith("G")) {
    int gcodeIndex = line.indexOf('G');
    String gcode = line.substring(gcodeIndex + 1, gcodeIndex + 3);
    int command = gcode.toInt();

    if (command == 0 || command == 1) { // G0 vagy G1 parancsok
      if (line.indexOf('X') >= 0) {
        int xIndex = line.indexOf('X');
        int nextSpace = line.indexOf(' ', xIndex);
        x = line.substring(xIndex + 1, nextSpace).toFloat();
      }
      if (line.indexOf('Y') >= 0) {
        int yIndex = line.indexOf('Y');
        int nextSpace = line.indexOf(' ', yIndex);
        y = line.substring(yIndex + 1, nextSpace).toFloat();
      }
      if (line.indexOf('Z') >= 0) {
        int zIndex = line.indexOf('Z');
        int nextSpace = line.indexOf(' ', zIndex);
        z = line.substring(zIndex + 1, nextSpace).toFloat();
      }
      sendCoordinates();
    }
  }
}

void sendCoordinates() {
  String coordinates = "X: " + String(x) + " Y: " + String(y) + " Z: " + String(z);
  mySerial.println(coordinates); // Küldés a másik sorosportra
}