#lang racket
(require "merl.rkt")

; Print an error message to standard error and exit
(define (err message)
  (eprintf "ERROR: ~a~n" message)
  (exit))

; Read MERL files from the command line arguments and store them in a list
(define input-merls
  (map (lambda (filename)
         (define in (open-input-file filename))
         (define m (read-merl in))
         (close-input-port in)
         m)
       (vector->list (current-command-line-arguments))))

; Link all the MERL files in the given list
(define (link-multiple merls)
  (cond
    [(empty? merls) (void)]
    [(empty? (rest merls)) (first merls)]
    [else (link-two (first merls) (link-multiple (rest merls)))]))

; Result of linking all the files
(define linked (link-multiple input-merls))

;; Function for linking two MERL files
;; Implement the linking algorithm here
(define (link-two m1 m2)
  ; Replace this with code that constructs the MERL file resulting from linking m1 and m2
  (define code (vector #x2410))
  (define table (list (entry REL HEADER-SIZE "")))
  (define end-code (+ HEADER-SIZE WORD-SIZE))
  (define end-module (+ end-code (* 2 WORD-SIZE)))
  (merl end-module end-code code table))

; Main program
; Output the result (as raw binary data)
(cond [(< (length input-merls) 2) (err "At least two MERL files must be provided as command line arguments.")]
      [else (write-merl linked)])
