/*
** PE Symbol Packer - 
**  Implements Object Rewriting for "Symbol Sets mark II"
*/

#include "mr4th_base.h"
#include "mr4th_stdio.h"
#include "mr4th_cmdln.h"
#include "mr4th_ascii.h"

#include "tinker/tinker_coff.h"

#include "mr4th_pe.symbol_pack.h"


#include "mr4th_base.c"
#include "mr4th_stdio.c"
#include "mr4th_cmdln.c"
#include "mr4th_ascii.c"

#include "tinker/tinker_coff.c"

////////////////////////////////
// PE Tabulator Argument Functions

MR4TH_SYMBOL_STATIC PESPK_Args*
pespk_args(Arena *arena, String8List *command_line_args){
  // parse
  CMDLN *cmdln = cmdln_from_args(arena, command_line_args);
  
  // setup args
  PESPK_Args *args = push_array(arena, PESPK_Args, 1);
  
  // get input file name
  args->input_file_name = cmdln_input_from_idx(cmdln, 0);
  args->output_file_name = cmdln_input_from_idx(cmdln, 1);
  
  return(args);
}

////////////////////////////////
// Entry Point

int main(int argc, char **argv){
  os_main_init(argc, argv);
  Arena *arena = arena_alloc();
  
  // arguments
  String8List command_line_args = os_command_line_arguments();
  PESPK_Args *args = pespk_args(arena, &command_line_args);
  
  // load input file
  String8 data = os_file_read(arena, args->input_file_name);
  
  // parse
  TNK_Coff *obj = tnk_coff_load_from_file(data);
  
  // merge .rpg* into .data
  {
    ArenaTemp scratch = arena_get_scratch(&arena, 1);
    
    U32 section_count = tnk_coff_section_count(obj);
    TNK_ID *sections = push_array(scratch.arena, TNK_ID, section_count);
    tnk_coff_section_get_all(obj, sections);
    
#if 0
    // TODO(allen): API wish
    TNK_ID *sections = tnk_coff_sections_get_all(arena, obj, &section_count);
#endif
    
    for (U32 i = 0; i < section_count; i += 1){
      TNK_ID section_id = sections[i];
      TNK_CoffSectionFields *fields = tnk_coff_section_fields(obj, section_id);
      if (str8_match(CLiteral(String8){fields->name, 8}, str8_lit(".rpg"),
                     StringMatchFlag_PrefixMatch)){
        MemoryCopy(fields->name, ".data\0\0\0", 8);
      }
    }
    
    arena_release_scratch(&scratch);
  }
  
  // generate
  {
    String8 gen_data = tnk_coff_generate(arena, obj);
    os_file_write(args->output_file_name, gen_data);
  }
  
}
