#include <plugin.h>

int scratchx = 10;
int scratchmove = 1;

#define PLUGIN_NAME "Old Movie"
#define RED(c)   ((c) & 0xFFL)
#define GREEN(c) (((c) & 0xFF00L) >> 8)
#define BLUE(c)  (((c) & 0xFF0000L) >> 16)
#ifndef RGB
#define RGB(r,g,b) ((r) | (g) << 8 | (b) << 16)
#endif

#define NUM_PARAM 2

VarStruct varstr[NUM_PARAM] = {
  {LABEL     , "In: 1 Strip", 0.0f, 0.0f, 0.0f, ""},
  {FLO|NUMSLI, "Area dirty", 0.1f, 0.0f, 1.0f, 
	"Average proportion \"broken\" pixels"},
};

typedef struct {
  int   dummy1;
  float rnd;
} Cast;

float cfra;

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

unsigned long togrey(unsigned long a)
{
  int c;

  c  = RED(a);
  c += GREEN(a);
  c += BLUE(a);
  c /= 3;

  return RGB(c, c, c);
}

/* ******************** Plugin 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 *param, float facf0, float facf1, int sx, int sy, 
	ImBuf *ibuf1, ImBuf *ibuf2, ImBuf *out, ImBuf *use)
{
  int a, spot;
  unsigned long *recto;
  unsigned long *recti;
  spot = (int)(32767.f * param->rnd);

  scratchx += scratchmove;
  if (scratchx < 0)
  {
    scratchx = 0;
    scratchmove = rand()%4 + 1;
  }
  if (scratchx >= sx)
  {
    scratchx = sx - 1;
    scratchmove = -(rand()%4 + 1);
  }
  if (rand() >= 16384) scratchmove++;
  if (rand() >= 16384) scratchmove--;
  if (scratchmove > 10) scratchmove = 10;
  if (scratchmove < -10) scratchmove = -10;

  if (rand() > 30000)
    if (rand() >= 16384)
      scratchmove = -(rand()%4 + 1);
    else
      scratchmove = (rand()%4 + 1);

  if(ibuf1)
  {
    recto = (unsigned long *)out->rect;
    recti = (unsigned long *)ibuf1->rect;
    a = sx * sy;
    while (a--)
    {
      *recto = togrey(*recti++);
      if (a % sx == scratchx || rand() < spot)
        *recto = 0x000000L;
      recto++;
    }
  }
  else
    printf ("Not linked to a buffer!\n");
}
