#include <string>
#include <iostream>
#include <stdexcept>
#include <fstream>
#include <queue>
#include "merl.h"

// Implement the linking algorithm in this function
MERL::MERL(MERL &m1, MERL &m2) {
  // Replace this with code that constructs the MERL file resulting from linking m1 and m2
  endCode = HEADER_SIZE + WORD_SIZE;
  endModule = endCode + 2 * (WORD_SIZE);
  code.push_back(0x2410);
  table.emplace_back(REL, HEADER_SIZE);
}

int main(int argc, char** argv) {
  try {
    std::queue<MERL> merls;
    for(int i=1; i<argc; ++i) {
      std::ifstream fs(argv[i]);
      if(fs.fail()) {
        throw std::runtime_error("Failed to open MERL file: "+std::string(argv[i]));
      }
      merls.push(MERL(fs));
    }
    if(merls.size() < 2) {
      throw std::runtime_error("At least two MERL files must be provided as command line arguments.");
    }
    MERL linked = merls.front();
    merls.pop();
    while(!merls.empty()) {
      MERL &m1 = linked;
      MERL &m2 = merls.front();
      linked = MERL(m1, m2);
      merls.pop();
    }
    linked.write(std::cout);
  } catch(std::runtime_error &e) {
    std::cerr << "ERROR: " << e.what() << '\n';
    return 1;
  }
  return 0;
}
