/* A program for halftoning an image using a 3 x 3 threshold array. Unlike
 *    convolution filters, the dither/halftone algorithm uses one value from 
 *    the 3x3 array to decide whether the channel for the pixel is 255 or 0.
 *    Thus, the red, green, and blue each have values of 255 or 0.
 *
 *    This program opens the P6 PPM image file whose name is on the command
 *    line, compares each channel to the corresponding threshold value and
 *    determines whether to set the color to 255 or 0, and outputs the result
 *    to standard out.
 */
//Yvon H. Feaster
//CPSC 215
// lab 9

import java.io.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.regex.*;

class DitherApp extends JPanel {
   private static final int WIDTH=1;
   private byte data[];
   private int dithered[];
   private boolean started = false;
   private int width, height;

   public DitherApp (String fileName) {
      JFrame frame = new JFrame (fileName);
      scanFile (fileName);
      dithered = new int [data.length];

      for (int i=0; i < data.length; ++i) {
         dithered[i] = (256+data[i])%256;
      } 
      
      frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
      frame.setLayout(new BorderLayout());
      JButton button = new JButton ("Convert");
      button.addActionListener (new ActionListener () {
         public void actionPerformed (ActionEvent e) {
            if (!started) {
               started = true;
               for (int i=0; i < height; ++i) {
                  // Create a thread to convert this row and start it.
                  new PixelThread(DitherApp.this, i).start();
               }
            }
         }
      });
      setSize (width * WIDTH, height * WIDTH);
      frame.add (this, BorderLayout.CENTER);
      frame.add (button, BorderLayout.SOUTH);
      frame.setSize(getWidth()+10, getHeight()+20);
      frame.setVisible (true);
   }
   
   public void setPixel (int row, int col, int rgb[]) {
      System.arraycopy (rgb, 0, dithered, (row*width + col)*3, 3);
   }
   
   public int[] getPixel (int row, int col) {
      int rgb[] = { dithered [(row*width+col)*3+0], 
                    dithered [(row*width+col)*3+1],
                    dithered [(row*width+col)*3+2] };
      return rgb;
   }                     
            
   public void paint (Graphics g) {
      for (int i=0; i < height; ++i) {
         for (int j=0; j < width; ++j) {
            ((Graphics2D) g).setPaint (new Color (dithered[(i*width+j)*3+0],
                                   dithered[(i*width+j)*3+1],
                                   dithered[(i*width+j)*3+2]));
            g.fillRect (j*WIDTH, i*WIDTH, WIDTH, WIDTH);
         }
      }
   }
   
   public int getWidth() { return width; }
   private void scanFile (String fileName) {
      try {
        scanHeader(fileName);
        scanData  (fileName);
      } catch (IOException e) {
         System.err.println (e);
      }
   }
   
   private void scanHeader (String fileName) throws IOException {
      FileInputStream in = new FileInputStream (fileName);
      Scanner scanner = new Scanner (in);
      
      // Read the file ID
      String id = scanner.next();
      
      // skip comments      
      Pattern comment = Pattern.compile("#.*");
      while (scanner.hasNext (comment)) {
         scanner.nextLine();
      }
      width = scanner.nextInt();

      // skip comments      
      while (scanner.hasNext (comment)) {
         scanner.nextLine();
      }
      height = scanner.nextInt();
      in.close();
   }
   
   private void scanData (String fileName) throws IOException {
   
      // Open the file with a data reader
      DataInputStream reader=new DataInputStream(new FileInputStream(fileName));

      // Using the difference between the number of bytes available and the
      //    number of data bytes, skip to the beginning of the data portion of 
      //    the file.
      reader.skipBytes (reader.available() - (width * height * 3));
      
      // allocate room for the RGB values of each pixel
      data = new byte [width * height * 3];

      // read in the data 
      reader.readFully(data);
   }


   public static void main (String args[]) throws IOException {
      if (args.length < 1) {
         System.err.println ("Usage: java DitherApp PPMfile");
      } else {
         new DitherApp (args[0]);
      }
   }
}

// Create a Thread sub class that converts a row of pixels, one at a time, with a 
//    .05 second pause and repaint after each convertion
class PixelThread extends Thread
{

   private int row;
   private DitherApp app;
   private static double threshold [][] = {{ .7*255, .9*255, .5*255},
                                           { .2*255, .1*255, .4*255},
                                           { .6*255, .3*255, .8*255} };

   // Create the constructor
   public PixelThread(DitherApp dither, int r)
   {
       super();
       row = r;
       app = dither;
   }
       
   
   // Complete the Thread run method
   // Applies a dither (or half tone) to a row of pixels, one at a time, with a
   //    .05 second pause and repaint after each convertion
   public void run ()
   {

          // Compare each channel of each pixel to the corresponding threshold.
          //    If the channel is greater than the threshold, it will be
         //    set to 255. Otherwise it will be set to 0. 
       // loops through all columns      
       for(int col = 0; col < app.getWidth(); ++col)
       {
          
          int pixIn[] = app.getPixel(row, col);
          for (int i=0; i<3; ++i)
          {
             pixIn[i]  = (pixIn[i] > threshold[row%3][col%3])? 255 : 0;
          }

          app.setPixel(row, col, pixIn);

          try{  
             sleep(50);
          }catch(InterruptedException e){  
             System.err.println(e);
          }  

          app.repaint();        
       }

    }
}

