
#include "macro.h"

static FILE * macro_file = NULL;

static Argument * macro_invoker (Argument *args);


void
macro_add (gchar * fmt,
           ...)
{
  va_list ap;
  if (macro_file)
    {
      va_start (ap, fmt);
      vfprintf (macro_file, fmt, ap);
      va_end (ap);
    }
}


ProcArg macro_args[] =
{
  { PDB_INT32,
    "action",
    "what to do: { MACRO-STOP (0), MACRO-START (1), MACRO-FLUSH (2)}"
  },
  { PDB_STRING,
    "filename",
    "the file to record to"
  }
};


ProcRecord macro_proc =
{
  "gimp_macro",
  "macro facility",
  "records macros",
  "Ray Lehtiniemi",
  "Ray Lehtiniemi",
  "1999",
  PDB_INTERNAL,

  /*  Input arguments  */
  2,
  macro_args,

  /*  Output arguments  */
  0,
  NULL,

  /*  Exec method  */
  { { macro_invoker } },
};


static Argument *
macro_invoker (Argument *args)
{
  int success = TRUE;
  gint action = 0;
  gchar * name = NULL;


  /* action */
  if (success)
    {
      action = args[0].value.pdb_int;
      switch (action)
        {
        case 0:
        case 1:
        case 2:
          break;
        default:
          success = FALSE;
        }
    }

  /* filename */
  if (success)
    {
      name = (gchar*) args[1].value.pdb_pointer;
      if (name == NULL)
        {
          success = FALSE;
        }
    }

  if (success)
    {
      switch (action)
        {
        case 0:
          if (macro_file)
            {
              fclose (macro_file);
              macro_file = NULL;
            }
          break;

        case 1:
          if (macro_file)
            {
              success = FALSE;
            }
          else
            {
              macro_file = fopen (name, "w");
              if (macro_file == NULL)
                {
                  success = FALSE;
                }
            }
          break;

        case 2:
          if (macro_file)
            {
              fflush (macro_file);
            }
          else
            {
              success = FALSE;
            }
          break;

        }
    }
  
  return procedural_db_return_args (&macro_proc, success);
}
