import java.applet.*; 
import java.awt.*; 
import java.awt.image.*; 
import java.awt.event.*; 
import java.io.*; 
import java.net.*; 
import java.text.*; 
import java.util.*; 
import java.util.zip.*; 

public class window extends BApplet {
// Window
// by bpaul <http://www.planet-hood.com/>

// Blur an image by processing it through a
// low-pass filter. Then display a small window that
// follows the mouse that shows the original image

// Created 9 December 2002
BImage a;  // the original image
BImage b;  // the blurred image

int n2 = 5/2;
int m2 = 5/2;
float  val = 1.0f/12.0f;

float[][] kernel = { {val, val, val, val, val},
{val, val, val, val, val},
{val, val, val, val, val},
{val, val, val, val, val},
{val, val, val, val, val} };

void setup ()
{
  size(400, 533);
  a = loadImage("Family2.jpg"); // Load the images into the program
  b = loadImage("Family2.jpg");


  // Convolve the image
  for(int y=0; y<height; y++) {
    for(int x=0; x<width; x++) {
      float sum = 0;
      for(int k=-n2; k<n2; k++) {
        for(int j=-m2; j<m2; j++) {
          // Reflect x-j to not exceed array boundary
          int xp = x-j;
          int yp = y-k;
          if (xp < 0) {
            xp = xp + width;
          } else if (x-j >= width) {
            xp = xp - width;
          }
          // Reflect y-k to not exceed array boundary
          if (yp < 0) {
            yp = yp + height;
          } else if (yp >= height) {
            yp = yp - height;
          }
          sum = sum + kernel[j+m2][k+n2] * red(a.pixels[xp+ yp*a.width]);
        }
      }

      int isum = (int)(sum);
      b.pixels[x + y*width] = color(isum, isum, isum);
    }
  }
  noBackground();

}


int once = 0;
int lastX = 0;
int lastY = 0;
int mx; 
int my; 
float delay = 20.0f; 

void loop()
{
  // Put blurred image into background the first time through the loop
  if (once == 0) {
    image(b, 0, 0); // Displays the image from point (0,0)
    once = 1;
  }
  
  // follow the mouse with delay
  if(abs(mouseX - mx ) > 1) { 
    mx = (int)(mx + (mouseX - mx)/delay); 
  } 
  if(abs(mouseY - my) > 1) { 
    my = (int)(my + (mouseY - my)/delay); 
  } 

  wipe (mx, my, 100, 100);
}

void wipe (int x, int y, int wwidth, int wheight)
{
  // constrain points to screen
  x = (int)(constrain (x, 0, width));
  y = (int)(constrain (y, 0, height));

  // if the mouse isn't pressed then replace the background
  if (!mousePressed) {
    for(int i=lastY; i<height && i < lastY+wheight; i++) {
      for(int j=lastX; j<width && j<lastX+wwidth; j++) {
        pixels[i*width + j] = b.pixels[i*width + j];
      }
    }
  }
  
  // draw the clear image
  for(int i=y; i<height && i < y+wheight; i++) {
    for(int j=x; j<width && j<x+wwidth; j++) {
      pixels[i*width + j] = a.pixels[i*width + j];
    }
  }
  
  // remember this point
  lastX = x;
  lastY = y;
}

}