//gcc -Wall -Werror `pkg-config --libs --cflags libming glib-2.0` compiler.c -o compiler

#include <glib.h>
#include <ming.h>
#include <string.h>

/* This is what is used to compile the Actionscript parts of the source to
 * includable C data that can later be executed.
 * Note that this is pretty much a hack until someone writes a proper
 * Actionscript compiler for Swfdec.
 * Also note that the creation of the include-scripts should probably not be 
 * autorun, as we don't want to depend on external bugs, only on internal ones.
 */
static gboolean
write_data (guint8 *data, int len)
{
  int i;

  for (i = 0; i < len; i++) {
    switch (i % 16) {
      case 0:
	if (i == 0)
	  g_print ("  0x%02X", data[i]);
	else
	  g_print (",\n  0x%02X", data[i]);
	break;
      case 4:
      case 8:
      case 12:
	g_print (",  0x%02X", data[i]);
	break;
      default:
	g_print (", 0x%02X", data[i]);
	break;
    }
  }
  g_print ("\n");
  return TRUE;
}

static char *
get_name (const char *filename)
{
  char *end;

  end = strrchr (filename, '/');
  if (end)
    filename = end + 1;
  end = strchr (filename, '.');
  if (end)
    return g_strndup (filename, end - filename);
  else
    return g_strdup (filename);
}

int
main (int argc, char **argv)
{
  SWFAction action;
  char *contents;
  GError *error = NULL;
  guint i;
  int len;
  gsize ignored;
  byte *data;

  if (argc < 2) {
    g_print ("usage: %s FILE ...\n\n", argv[0]);
    return 1;
  }

  Ming_init ();
  Ming_setSWFCompression (-1);

  g_print ("/* This file is autogenerated, do not edit! */\n\n");
  for (i = 1; i < argc; i++) {
    if (!g_file_get_contents (argv[1], &contents, NULL, &error)) {
      g_printerr ("Error: %s\n", error->message);
      g_error_free (error);
      error = NULL;
      return 1;
    }
    action = newSWFAction (contents);
    if (SWFAction_compile (action, 6, &len) != 0) {
      g_printerr ("Error: Couldn't compile\n");
      return -1;
    }
    data = SWFAction_getByteCode (action, &ignored);
    contents = get_name (argv[i]);
    g_print ("/* compiled from %s */\n", argv[i]);
    g_print ("static const unsigned char %s[] = {\n", contents);
    g_free (contents);
    write_data (data, len);
    g_print ("};\n\n");
  }
  return 0;
}
