(*naloga encoderja je, da pretvarja iz lineSemantic tipa v stringe ki jih appendamo v object file*)

open SemanticAnalyzer
(*vrne H vrstico*)
let getZaglavjeAndStart (prviUkaz : lineSemantic) (lenProg : int) : string list * int = 
  let name = match prviUkaz.label with
  | None -> "MOJPROG" (*default ime*)
  | Some s -> if String.length s > 6 then "MOJPROG" else String.make (6 - String.length s) '0' ^ s (*paddamo z 0 če je < 6*)
  in
  let startAddrString, startAddrInt  = match prviUkaz.mnem with
  | MnemonicDn s ->  (*preverimo ali je pravilne dolzine in naredimo string dolzine 6*) 
    let n = int_of_string s in
    if n < 0 || n > 0xFFFFFF then
      invalid_arg "getZaglavje: zacetni naslov out of range"
    else
      (Printf.sprintf "%06X" n), n 
  | _ -> failwith "getZaglavje: invalid mnemonic_type"
  in
  let lenObjectCode = Printf.sprintf "%06X" lenProg in 
  ["H" ^ name ^ startAddrString ^ lenObjectCode], startAddrInt(*vrnemo concatiniran string in startAddr*)


(*vrne T vrstico*)  
let instructionList_to_objectCode (instructionList : string list) (startAddr : int) : string = 

  let startAddr = Printf.sprintf "%06X" startAddr in 
  let objectCode = String.concat "" instructionList in
  let len = (String.length objectCode)  / 2 in (*delimo z dva ker hočemo dolžino v bytih ne nibblih*)
  let lenString = Printf.sprintf "%02X" len in 
  "T" ^ startAddr ^ lenString ^ objectCode (*vrnemo concatiniran T zapis*)

(*vrne E vrstico*)
let getEnd (start : int) : string = 
  let start = Printf.sprintf "%06X" start in 
  "E" ^ start