#!/bin/bash
# csv_to_hex.sh - Konvertiert CSV mit Hex-Nibbles zu Binärdatei und Intel HEX
#
# Eingabe: CSV-Datei mit einem Byte pro Zeile, Nibbles Space-getrennt
#          z.B. "0 9" -> 0x09
# Ausgabe: .bin (Binärdatei) und .hex (Intel HEX Format)

set -euo pipefail

if [ $# -lt 1 ]; then
    echo "Verwendung: $0 <eingabe.csv> [ausgabe_prefix]"
    echo "Beispiel:   $0 EPROM_Rad_5.csv EPROM_Rad_5"
    exit 1
fi

INPUT="$1"
PREFIX="${2:-${INPUT%.csv}}"

BINFILE="${PREFIX}.bin"
HEXFILE="${PREFIX}.hex"

if [ ! -f "$INPUT" ]; then
    echo "Fehler: Datei '$INPUT' nicht gefunden."
    exit 1
fi

echo "=== CSV zu Intel HEX Konverter ==="
echo "Eingabe:  $INPUT"
echo "Binär:    $BINFILE"
echo "Intel HEX: $HEXFILE"
echo ""

# Schritt 1: CSV -> Binärdatei
# Jede Zeile enthält zwei Nibbles (High Low), z.B. "0 9" -> Byte 0x09
> "$BINFILE"  # Datei leeren/erstellen

while IFS=' ' read -r high low rest; do
    # Leere Zeilen überspringen
    [ -z "$high" ] && continue
    # Nibbles zusammensetzen
    byte="${high}${low}"
    # Als Binärbyte schreiben
    printf "\\x${byte}" >> "$BINFILE"
done < "$INPUT"

FILESIZE=$(stat -c %s "$BINFILE" 2>/dev/null || stat -f %z "$BINFILE")
echo "Schritt 1: Binärdatei erstellt ($FILESIZE Bytes)"

# Schritt 2: Binärdatei -> Intel HEX Format
objcopy -I binary -O ihex "$BINFILE" "$HEXFILE"
echo "Schritt 2: Intel HEX Datei erstellt"

echo ""
echo "=== Ergebnis ==="
echo ""
echo "--- Hex-Dump der Binärdatei (xxd) ---"
xxd "$BINFILE"
echo ""
echo "--- Intel HEX Datei ---"
cat "$HEXFILE"
echo ""
echo "Fertig. '$HEXFILE' kann direkt in einen EEPROM-Programmierer geladen werden."
