#include <plugin.h>

#define COLORREF unsigned long

#define PLUGIN_NAME "Speckle";

#define NUM_PARAM 2
VarStruct varstr[NUM_PARAM] = {
  {LABEL,   "In: 2 strips", 0.0f, 0.0f, 0.0f, ""},
  {INT|TOG, "shimmer", 0.0f, 0.0f, 1.0f, "increment seed each frame"},
};

/* The cast struct is for input in the main doit function
   Varstr and Cast must have the same variables in the same order */

typedef struct {
  int dummy;
  int shimmer;
} Cast;

/* cfra: the current frame */

float cfra;

void plugin_seq_doit(Cast *, float, float, int, int, ImBuf *, ImBuf *, 
	ImBuf *, ImBuf *);

int useseed = 0;

/* ******************** Fixed functions ***************** */

int plugin_seq_getversion(void)
{
  return B_PLUGIN_VERSION;
}

void plugin_but_changed(int but)
{
}

void plugin_init(void)
{
}

void plugin_getinfo(PluginInfo *info)
{
  info->name = PLUGIN_NAME;

  info->nvars = NUM_PARAM;
  info->varstr = varstr;

  info->cfra = &cfra;

  info->init = plugin_init;
  info->seq_doit = (SeqDoit)plugin_seq_doit;
  info->callback = plugin_but_changed;
}

void plugin_seq_doit(Cast *cast, float facf0, float facf1, int sx, int sy, ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *out, ImBuf *use)
{
  int a;
  COLORREF *recto;
  COLORREF *recti1;
  COLORREF *recti2;
  int n;

  /* calculate random number limit */
  n = (int)((float)RAND_MAX * facf0);
  /* if shimmer is off, the random numbers will take the same
     sequence each frame, so the number generated for each pixel
     will be the same, but the limit (n) is higher each frame
     so pixels will gradually appear */
  srand (useseed);
  if (cast->shimmer)
    useseed++;

  if(ibuf1 && ibuf2)
  {
    a= ibuf1->x*ibuf1->y;
    recto = (COLORREF *)out->rect;
    recti1 = (COLORREF *)ibuf1->rect;
    recti2 = (COLORREF *)ibuf2->rect;
    while(a--) {
      *recto = (rand() <= n) ? *recti2 : *recti1;
      recto++; recti1++; recti2++;
    }
  }
  else
    printf ("Not linked to 2 buffers!\n");
}
