#! /usr/local/bin/pvtool

#define NO_OUTPUT 1

#define USAGE_MESSAGE "\
\tpvresyn <input pv file> <output audio file> [<Csound ksmps>]\n\
\n\
This simple utility resynthesizes an audio file from a phase vocoder file.\n\
It works by shelling out to Csound. The Ksmps used by Csound can be set and\n\
defaults to 50.\n"

#define CSOUND_CALL "csound -Wo %s %s %s"
/* 'W' Because want WAV output. Change to 'A' for AIFF. */

#define DEFAULT_KSMPS 50 /* I don't really know what to default this too
			    - I would do some thinking/testing but don't
			    have time now. */

int
pvaction (void)
{
  int err = 0, ksmps = DEFAULT_KSMPS, sr, kr;
  FILE *score, *orchestra;
  char scorename[L_tmpnam], orchestraname[L_tmpnam];
  char command[L_tmpnam * 2 + 100];	/* Needs space for csound call +
      				       output filename */


  if (parameter_count < 1)
    err = pvtool_error ("No output filename given.");

  if (!err)
    {
      if (parameter_count >= 2)
	ksmps = (int) (0.5 + fparameter[1]);
      sr = (int) (0.5 + sampling_rate ());

      kr = sr / ksmps;
      if (kr * ksmps != sr)
	err = pvtool_error ("Ksmps value does not work with sampling rate.\n");
    }

  if (!err)
    {
      if (tmpnam (scorename) == NULL || tmpnam (orchestraname) == NULL)
	err = pvtool_error ("Failed to generate temporary file.\n");
    }

  if (!err)
    {
      score = fopen (scorename, "w");
      orchestra = fopen (orchestraname, "w");
      if (score == NULL || orchestra == NULL)
	err = pvtool_error ("Failed to open temporary file.\n");
    }

  if (!err)
    {
      fprintf (score,
	       "; This score was generated automatically by pvresyn\n");
      fprintf (score,
	       "i1 0 %f\n",
	       sound_length (1));

      fprintf (orchestra,
	       "; This orchestra was generated automatically by pvresyn\n");
      fprintf (orchestra, "sr = %d\nkr = %d\nksmps = %d\n\n", sr, kr, ksmps);
      fprintf (orchestra,
	       "instr 1\nkctrl linseg 0,p3,p3\na1 pvoc kctrl,1,\"%s\"\nout a1\nendin\n",
	       input_filename (1));
    }

  if (!err)
    {
      fclose (score);
      fclose (orchestra);

      sprintf (command,
	       CSOUND_CALL,
	       parameter[0],
	       orchestraname,
	       scorename);

      system(command);

      remove (scorename);
      remove (orchestraname);
      remove ("score.srt");
    }

  return (err);
}
