/**
    dump the contents of a file saved by simcore

    Copyright (c) 2020-2022 The Creators of Simphone

    See the file COPYING.LESSER.txt for copying permission.
**/

#include "simapi.h"
#include "file.h"

#include <stdio.h>

#ifndef _WIN32
#include <unistd.h>
#else
#define STDOUT_FILENO 1
#endif

int main (int argc, char **argv) {
  int err;
  char *name, *s;
  simtype table, key, val;
  simwalker ctx;
  if (argc < 2) {
    fprintf (stderr, "usage: %s <filename>\n", argv[0]);
    return -1;
  }
  for (name = s = argv[1]; *s; s++)
    if (*s == '/' || *s == *FILE_DIRECTORY_SLASH)
      name = s + 1;
  sim_init_bits (SIM_INIT_BIT_NOCRASH | SIM_INIT_BIT_NOAUDIO);
  if ((err = sim_init_ (NULL, 0, "simdump")) != SIM_OK) {
    fprintf (stderr, "init: %s (error %d)\n", sim_error_get (err), err);
    return -2;
  }
  if ((err = log_init_fd_ (STDOUT_FILENO)) != SIM_OK) {
    fprintf (stderr, "log: %s (error %d)\n", sim_error_get (err), err);
    sim_exit_ ();
    return -3;
  }
  sim_protect_ ();
  if ((err = _file_load (argv[1], FILE_TYPE_PLAINTEXT | FILE_TYPE_TEMPORARY, &table, name, 0)) != SIM_OK)
    if ((err = _file_load (argv[1], FILE_TYPE_PLAINTEXT | FILE_TYPE_TEMPORARY, &table, NULL, 0)) == SIM_OK)
      for (sim_table_walk_first (&ctx, table); sim_get_type (val = sim_table_walk_next_string (&ctx, &key)) != SIMNIL;)
        if (sim_get_length (key) > 2 && sim_get_pointer (key)[0] == '.' && sim_get_pointer (key)[1] == '/') {
          err = _file_load (argv[1], FILE_TYPE_PLAINTEXT | FILE_TYPE_TEMPORARY, &val, &sim_get_pointer (key)[2], 0);
          if (err == SIM_OK)
            table = val;
          err = SIM_OK;
          break;
        }
  sim_unprotect_ ();
  if (err != SIM_OK) {
    fprintf (stderr, "load: %s (error %d)\n", sim_error_get (err), err);
    sim_exit_ ();
    return -4;
  }
  log_simtype_ ("", SIM_LOG_ERROR, table, 0, " ");
  sim_table_free (table);
  sim_exit_ ();
  return 0;
}
