open Processor
(* Convert hex string to int *)
let int_of_hex s = int_of_string ("0x" ^ s)

(* Convert two hex digits to a char *)
let char_of_hex s = Char.chr (int_of_hex s)

(* Write a list of bytes (chars) to memory at a given start address *)
let write_bytes state start bytes =
  List.iteri (fun i byte -> Bytes.set state.memory (start + i) byte) bytes

(* Parse a T record line like: TAAAAAALL[BYTECODES...] *)
let parse_text_record line =
  (* Skip leading 'T' *)
  let line = String.sub line 1 (String.length line - 1) in
  if String.length line < 8 then failwith "T record too short";
  let start_str = String.sub line 0 6 in (*pridobi stolpce 2-7*)
  let len_str = String.sub line 6 2 in (*pridobi stolpce 8-9*)
  let start_addr = int_of_hex start_str in (*izračunaj star addr*)
  let _ = int_of_hex len_str in (*izračunaj dolžino -> v bistvu je nikjer ne rabimo*)
  let byte_str = String.sub line 8 (String.length line - 8) in (*pridobi stolpce 10-*)
  (* Split the string into pairs of hex digits *)
  let bytes =
    let rec aux i acc =
      if i >= String.length byte_str then List.rev acc (*ko si na koncu še obrni listo, ker si dodajal na začetek *)
      else
        let hex_pair = String.sub byte_str i 2 in (*pridobi par črk*)
        aux (i + 2) (char_of_hex hex_pair :: acc) (*dodaj na začetek nov par*)
    in
    aux 0 []
  in
  (start_addr, bytes)

(* Load a SIC/XE object file into memory *)
let load_object_file (state : Processor.state) (filename : string) : unit  =
  let ic = open_in filename in
  try
    while true do
      let line = input_line ic in
      match line.[0] with
      | 'T' ->
          let addr, bytes = parse_text_record line in
          write_bytes state addr bytes
      | 'H' -> ()  (* header: can parse start addr/length if needed *)
      | 'E' -> ()  (* end: can parse entry point if needed *)
      | _ -> ()
    done
  with
  | End_of_file -> close_in ic
