#! /usr/local/bin/pvtool

#define NO_OUTPUT 1
#define USAGE_MESSAGE "\
\tspecgram <input pv file>\n\
\n\
This program plots a pv file as a spectrogram.\n"

#define GREY_SCALE 10
#define GREY_LEVELS 101
/* NB GREY_LEVELS/GREY_SCALE gives the maximum bin magnitude: everything
   beyond this is just black. I normally aim to leave GREY_LEVELS/GREY_SCALE
   around 10. */

#define CHARS_PER_PIXEL 2	/* This has to go to 2 if you increase the
			     GREY_LEVELS enough. */

char num_to_str_buff[3];

char *
num_to_str (int level)
{
  if (CHARS_PER_PIXEL == 2)
    {
      num_to_str_buff[0] = 'A' + level % 26;
      num_to_str_buff[1] = 'A' + level / 26;
      num_to_str_buff[2] = '\0';
    }
  else
    /* ie 1 */
    {
      num_to_str_buff[0] = 'A' + level;
      num_to_str_buff[1] = '\0';
    }
  return (num_to_str_buff);
}

int
pvaction (void)
{
  int i, j, c;
  FILE *handle;

  char filename[L_tmpnam], command[L_tmpnam + 3];

  if (tmpnam (filename) == NULL)
    {
      pvtool_error ("Failed to generate temporary file\n");
      return (-1);
    }

  handle = fopen (filename, "w");

  fprintf (handle, "/* XPM */\n");
  fprintf (handle, "static char * disp[] = {\n");
  fprintf (handle, "/* pvtool bitmap\n");
  fprintf (handle, " * width height ncolors chars_per_pixel  */\n");
  fprintf (handle, "\"%d %d %d %d \",\n",
	   INPUT1_FRAMES,
	   bins,
	   GREY_LEVELS,
	   CHARS_PER_PIXEL);
  for (i = 0; i < GREY_LEVELS; i++)
    fprintf (handle,
	     "\"%s c grey%d \tm %s \ts s_grey%d \",\n",
	     num_to_str (i),
	     (100 * i) / (GREY_LEVELS - 1),
	     (i * 2 < GREY_LEVELS) ? "black" : "white",
	     (100 * i) / (GREY_LEVELS - 1));

  fprintf (handle, "/* Pixels: */\n");

  for (j = bins - 1; j >= 0; j--)
    {
      fprintf (handle, "\"");
      for (i = 0; i < INPUT1_FRAMES; i++)
	{
	  c = (int) (GREY_SCALE * INPUT1_MAG (i, j));
	  if (c < 0)
	    c = 0;
	  if (c >= GREY_LEVELS)
	    c = GREY_LEVELS - 1;
	  fprintf (handle, "%s", num_to_str (GREY_LEVELS - c - 1));
	}
      fprintf (handle, "\"");
      if (j != 0)
	fprintf (handle, ",\n");
    }

  fprintf (handle, "\n} ;\n");

  fclose (handle);

  sprintf (command, "xv %s", filename);
  system (command);

  remove (filename);

  return (0);
}
