
import ij.IJ;
import ij.ImagePlus;
import ij.gui.NewImage;
import ij.plugin.filter.PlugInFilter;
import ij.process.Blitter;
import ij.process.ImageProcessor;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.border.TitledBorder;
import javax.swing.JCheckBox;
import javax.swing.JRadioButton;
import javax.swing.UIManager;
import javax.swing.JTextArea;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ButtonGroup;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import java.awt.Color;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.Font;

/**
*
* Plugin ImageJ Steganografia Digitale: Coder
*
* @author Massimiliano Portelli
* @author Roberto Di Perna
* 
*/

public class Coder_ implements PlugInFilter {
	private ImagePlus imp;
	private ImageProcessor ip;
	private File file;
	private int h, w, x, y, xMin, xMax, yMin, yMax;

	private JFrame frmCoder;
	
	private JCheckBox redCBox;
	private JCheckBox greenCBox;
	private JCheckBox blueCBox;
	private JRadioButton red1RBox;
	private JRadioButton red2RBox;
	private JRadioButton green1RBox;
	private JRadioButton green2RBox;
	private JRadioButton blue1RBox;
	private JRadioButton blue2RBox;
	private final ButtonGroup redGroup = new ButtonGroup();
	private final ButtonGroup greenGroup = new ButtonGroup();
	private final ButtonGroup blueGroup = new ButtonGroup();
	
	private JLabel daLabel;
	private JLabel aLabel;
	private JTextField xText;
	private JTextField yText;
	
	private JCheckBox cifraturaCBox;
	private JPasswordField passwordField;
	private JComboBox saltoBox;
	private JCheckBox keyCBox;
	
	private JComboBox typeBox;
	private JButton browseButton;
	private JTextArea textArea;
	
	private JLabel maxLabel;
	
	
	
	private void startCode() {
		//controola che sia selezionato almeno un piano colore
		if (!redCBox.isSelected() && !greenCBox.isSelected() && !blueCBox.isSelected()) {
			IJ.showMessage("Selezionare almeno un piano colore!");
			return;
		}
		
		
		//controlla x e y
		if (!setX()) { //setX() richiama anche setY()
			return;
		}
		
		
		//buf conterrà i byte del messaggio
		byte[] buf;
		
		
		//verifica che il testo/file sia stato inserito correttamente e lo riversa nell'array buf
		String input = textArea.getText();
		if (typeBox.getSelectedIndex() == 0) { //testo
			if (input.equals("")) {
				IJ.showMessage("Nessun testo inserito!");
	            return;
			}
			
			buf = input.getBytes();
			
			//verifica dimensioni
			if (buf.length > calcMax()) {
				IJ.showMessage("Testo troppo grande!");
				return;
			}			
		}
		else  {	//file
			if (input.equals("")) {
				IJ.showMessage("Nessun file inserito!");
	            return;
			}
			try {
				FileInputStream fis = new FileInputStream(file);
				buf = new byte[fis.available()]; //crea un array di byte per contenere il file
		        fis.read(buf); //riversa il contenuto del file in buf
		        fis.close();
		        
		        buf = addTitle(buf, file.getName().getBytes()); //aggiunge il titolo del file all'inizio di buf
		        
		        //verifica dimensioni
		        if (buf.length-1 > calcMax()) { //-1 è per il byte di lunghezza titolo
					IJ.showMessage("File+titolo troppo grandi!");
					return;
				}		        
			}
			catch (FileNotFoundException e) {
				IJ.showMessage("ERRORE - File non trovato!");
	            return;
			}
			catch (IOException e) {
				IJ.showMessage("ERRORE file!\n"+e.getMessage());
				e.printStackTrace();
	            return;
			}
		}
		
		
		//se richiesto cifra il messaggio
		if (cifraturaCBox.isSelected()) {
			char[] password = passwordField.getPassword();
			if (password.length == 0) {
				IJ.showMessage("Inserire password!");
				return;
			}
			try {
				buf = encrypt(buf, password);
			}
			catch (Exception e) {
				IJ.showMessage("ERRORE cifratura!\n"+e.getMessage());
				e.printStackTrace();
				return;
			}
		}
		
		buf = addMsgDim(buf); //aggiunge la dimensione del messaggio prima dello stesso
		int[] bits = byteToBinary(buf); //converte buf in "bit"
		
		String titoloOriginale = imp.getTitle();
		
		//creo una nuova immagine
		ImagePlus steganografia = NewImage.createRGBImage("stego_"+titoloOriginale, w, h, 1, NewImage.FILL_BLACK);
		//creo il processore per l'immagine
		ImageProcessor ip_ste = steganografia.getProcessor();
		//copio i valori nell'immagine da modificare 
		ip_ste.copyBits(ip, 0, 0, Blitter.COPY);
		
		if (keyCBox.isSelected()) insertKey(ip_ste); //inserisce la chiave nell'immagine
		insertMessage(ip_ste, bits); //inserisce il messaggio nell'immagine
		
		steganografia.show();
		steganografia.updateAndDraw();
		
		frmCoder.dispose();
	}
	
	
	
	private void insertKey(ImageProcessor ip_ste) {
		byte[] key = new byte[6]; //contiene la chiave senza delimitatori (1 byte per cifratura,tipo,bit piani; 1 byte per il salto; 2 byte per X; 2 byte per Y)
		
		
		//il 1° bit del primo byte indica se è il messaggio è cifrato o no
		if (cifraturaCBox.isSelected()) {
			key[0] = (byte) 0x80; // 10000000
		}
		else {
			key[0] = 0x00; // 00000000
		}
		
		//il 2° bit del primo byte indica se il messaggio è un testo o un file
		//se typeBox è settato a 0 non c'è bisogno di fare nulla, se è settato a 1 bisogna cambiare il 2° bit 
		if (typeBox.getSelectedIndex() == 1) {
			key[0] = (byte) (key[0] | 0x40); // 01000000
		}
		
		//setta i bit dal 3° all'8° del primo byte per dire quali bit dei piani colore utilizzare		
		if (redCBox.isSelected()) {
			key[0] = (byte) (key[0] | 0x20); // 00100000
			if (red2RBox.isSelected()) key[0] = (byte) (key[0] | 0x10); // 00010000
		}
		if (greenCBox.isSelected()) {
			key[0] = (byte) (key[0] | 0x08); // 00001000
			if (green2RBox.isSelected()) key[0] = (byte) (key[0] | 0x04); // 00000100
		}
		if (blueCBox.isSelected()) {
			key[0] = (byte) (key[0] | 0x02); // 00000010
			if (blue2RBox.isSelected()) key[0] = (byte) (key[0] | 0x01); // 00000001
		}
		
		
		//setta i byte 1-4 per contenere x e y (x e y sono int e devono essere >=0, quindi basta salvare gli ultimi 2 byte di ogni int)
		key[1] = (byte)((x & 0x0000FF00) >> 8);
		key[2] = (byte)((x & 0x000000FF)     );
		key[3] = (byte)((y & 0x0000FF00) >> 8);
		key[4] = (byte)((y & 0x000000FF)     );
		
		
		//setta il byte 5 per contenete il valore del salto (0-255)
		key[5] = (byte) saltoBox.getSelectedIndex();
		
		
		int[] bits = byteToBinary(key); //converte la chiave in bit
		bits = addLimits(bits); //aggiunge i delimitatori
		
		
		int[] aux = new int[3];// array in cui andremo a salvare i valore dei pixel RGB
		int pos = 0;//scorre l'array di bit dell'immagine
		
		//inserisce la chiave con i delimitatori nell'immagine
		for (int v = 0; v < h; v++) {
			if (pos > bits.length-1) break;//esce se pos e maggiore del numero dei bit della stringa
			for (int u = 0; u < w; u++) {
				//modifichiamo i bit meno significativi dei 3 canali
				ip_ste.getPixel(u, v, aux);// in aux vengono messi i valori RGB del pixel di posizione [i][j]
				if (pos < bits.length) aux[0] = (aux[0] & 0xFE) | bits[pos++];
				if (pos < bits.length) aux[1] = (aux[1] & 0xFE) | bits[pos++];
				if (pos < bits.length) aux[2] = (aux[2] & 0xFE) | bits[pos++];
				ip_ste.putPixel(u, v, aux);//mettiamo i nuovi valori modificati nel pixel [i][j]
				
				if (pos > bits.length-1) break;
			}
		}		
	}
	
	
	
	private void insertMessage(ImageProcessor ip_ste, int[] bits) {
		int[] aux = new int[3];// array in cui andremo a salvare i valore dei pixel RGB 
		int pos = 0;//scorre l'array di bit dell'immagine
		
		int salto = saltoBox.getSelectedIndex();
		int saltoCont = salto;
		
		for (int v = x; v < h; v++) {
			if (pos > bits.length-1) break;//esce se pos è maggiore del numero dei bit della stringa
			for (int u = (v==x ? y : 0); u < w; u++) { //u dipende da quale riga ci troviamo
				if (saltoCont == salto) {
					//modifichiamo i bit meno significativi dei 3 canali
					ip_ste.getPixel(u, v, aux);// in aux vengono messi i valori RGB del pixel di posizione [i][j]
					if (redCBox.isSelected()) {
						if (pos < bits.length) aux[0] = (aux[0] & 0xFE) | bits[pos++];
						if (red2RBox.isSelected() && pos < bits.length) aux[0] = (aux[0] & 0xFD) | (bits[pos++]<<1);
					}
					if (greenCBox.isSelected()) {
						if (pos < bits.length) aux[1] = (aux[1] & 0xFE) | bits[pos++];
						if (green2RBox.isSelected() && pos < bits.length) aux[1] = (aux[1] & 0xFD) | (bits[pos++]<<1);
					}
					if (blueCBox.isSelected()) {
						if (pos < bits.length) aux[2] = (aux[2] & 0xFE) | bits[pos++];
						if (blue2RBox.isSelected() && pos < bits.length) aux[2] = (aux[2] & 0xFD) | (bits[pos++]<<1);
					}
					ip_ste.putPixel(u, v, aux);//mettiamo i nuovi valori modificati nel pixel [i][j]
					saltoCont = 0;
				}
				else saltoCont++;
				
				if (pos > bits.length-1) break;
			}
		}
	}
	
	
	
	private int[] byteToBinary(byte[] buf) 
	{
		int[] binary = new int[buf.length*8];
		int pos = 0; //serve per scorrere l'array binario
		for (byte b : buf) 
		{
			int val = b;
			for (int i = 0; i < 8; i++)
			{
				binary[pos] = (val & 128) == 0 ? 0 : 1;
				val <<= 1; //shifta il byte a sinistra di 1 posizione
				pos++;
			}
		}
		
		return binary;		
	}
	
	
	
	//ritorna l'array di byte che rappresenta il messaggio criptato con password
	public byte[] encrypt(byte[] buf, char[] password) throws Exception {
		String algoritmo = "PBEWithMD5AndDES";
		byte[] salt = "a9v5n38s".getBytes(); //dovrebbe essere generato casualmente
		
		//creo pbeParamSpec e secretKey (basata sulla password) da passare successivamente a Cipher
		PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt,20);
		PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
		SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(algoritmo);
		SecretKey secretKey = secretKeyFactory.generateSecret(pbeKeySpec);

		//creo il motore di criptazone
		Cipher cipher = Cipher.getInstance(algoritmo);
		//lo inizializzo
		cipher.init(Cipher.ENCRYPT_MODE,secretKey,pbeParamSpec);
		
		//cripto la sequenza di byte
		byte[] risultato = cipher.doFinal(buf);
		return risultato;
	}
	
	
	
	private int[] addLimits(int[] binary) 
	{
		int j;
		int[] binaryPlus = new int[binary.length+16];
		
		//aggiunge il byte (0x02) all'inizio
		binaryPlus[6] = 0x01;
		
		//ricopia i bit della chiave
		int i=8;
		for (j=0 ; j<binary.length; j++)
		{
			binaryPlus[i++] = binary[j];
		}
		
		//aggiunge il byte (0x03) alla fine
		binaryPlus[binaryPlus.length-2] = 0x01;
		binaryPlus[binaryPlus.length-1] = 0x01;
		
		return binaryPlus;
	}
	
	
	
	private byte[] addMsgDim(byte[] buf) {
		int bufDim = buf.length;
		byte[] bufPlus = new byte[bufDim+2];
		
		//inserisco i 2 byte meno significativi di bufDim che mi indicano la dimensione del messaggio
		bufPlus[0] = (byte)((bufDim & 0x0000FF00) >> 8);
		bufPlus[1] = (byte)((bufDim & 0x000000FF)     );

		//ricopio i byte di buf in bufPlus
		for (int i=0; i<buf.length; i++) {
			bufPlus[i+2] = buf[i];
		}
		
		return bufPlus;
	}
	
	
	
	private byte[] addTitle(byte[] buf, byte[] title) {
		int bufDim = buf.length;
		int titleDim = title.length;
		byte[] bufPlus = new byte[1+titleDim+bufDim];
		
		//inserisco 1 byte per indicare la dimensione del titolo
		bufPlus[0] = (byte)(titleDim & 0x000000FF);
		
		//ricopio i byte di title in bufPlus
		for (int i=0; i<title.length; i++) {
			bufPlus[1+i] = title[i];
		}
		
		//ricopio i byte di buf in bufPlus
		for (int i=0; i<buf.length; i++) {
			bufPlus[1+titleDim+i] = buf[i];
		}
		
		return bufPlus;
	}
	
	
	
	private void calcPixelLimits() {
		//controlla se è stato scelto di inserire la chiave
		if (keyCBox.isSelected()) {
			// gli 8 byte di chiave vanno nei primi 21,3(cioè 22) pixel
			if (w > 22) {
				xMin = 0;
				yMin = 22;
			}
			else {
				xMin = 22/w;
				yMin = (22%w);			
			}
		}
		else {
			xMin = 0;
			yMin = 0;
		}
		daLabel.setText("Da ("+ xMin +","+ yMin +")");
		
		//controlla che x e y non eccedano il massimo valore assumile da un int
		if (h <= 2147483647) xMax = h-1;
		else xMax = 2147483646; //non 2147483647 perchè parte da 0
		if (w <= 2147483647) yMax = w-1;
		else yMax = 2147483646; //non 2147483647 perchè parte da 0
		aLabel.setText("A ("+xMax+","+yMax+")");
	}
	
	
	
	private long calcMax() {
		int pixelPlanes = 0;
		if (redCBox.isSelected()) {
			pixelPlanes++;
			if (red2RBox.isSelected()) pixelPlanes++;
		}
		if (greenCBox.isSelected()) {
			pixelPlanes++;
			if (green2RBox.isSelected()) pixelPlanes++;
		}
		if (blueCBox.isSelected()) {
			pixelPlanes++;
			if (blue2RBox.isSelected()) pixelPlanes++;
		}
		
		//numero di pixel da saltare fino al pixel iniziale
		long pixelSkipped = (((x+1)*w) - (w - (y+1)))-1;
		
		//numero di pixel utilizzabili
		long pixelUsable = ((h*w)-pixelSkipped) / (saltoBox.getSelectedIndex()+1);
		if ( ((h*w)-pixelSkipped) % (saltoBox.getSelectedIndex()+1) != 0 ) pixelUsable++;
		
		//numero massimo di byte inseribili come messaggio
		long max = ((pixelUsable*pixelPlanes) / 8) - 2; //-2 per i byte di dimensione messaggio
		if (max<0) max = 0;
		else if (max>2147483647) max = 2147483647;
		
		//la cifratura produce array multipli di 8 byte (1-7byte => 8byte)
		if (cifraturaCBox.isSelected()) max = max - ((max%8)+1);
		if (max<0) max = 0;
		
		if (typeBox.getSelectedIndex() == 0) { //testo
			maxLabel.setText("Max caratteri: "+max);
		}
		else { //file
			max--; //per il byte di dimensione del titolo file
			if (max<0) max = 0;
			maxLabel.setText("Max byte (file+titolo): "+max);
		}
		
		return max;
	}
	
	
	
	private boolean setX() {
		boolean result = true;
		
		try {
			int temp = Integer.parseInt(xText.getText());
			if (temp < xMin || temp > xMax) {
				IJ.showMessage("X deve essere nel range: "+xMin+" - "+xMax);
				
				if (x < xMin || x > xMax) x = xMin;
				result = false;				
			}
			else x = temp;
		}
		catch (NumberFormatException ex) {
			IJ.showMessage("ERRORE - X: numero non valido!");
		}
		
		xText.setText(""+x);
		
		if (!setY()) result = false;
		
		return result;
	}
	
	
	
	private boolean setY() {
		boolean result = true;
		
		try {
			int temp = Integer.parseInt(yText.getText());
			if (x <= xMin && (temp < yMin || temp > yMax)) {
				IJ.showMessage("Y deve essere nel range: "+yMin+" - "+yMax);
				
				if (y < yMin || y > yMax) y = yMin;
				result = false;
			}
			else if (temp < 0 || temp > yMax) {
				IJ.showMessage("Y deve essere nel range: 0 - "+yMax);

				if (y < 0 || y > yMax) y = yMin;
				result = false;
			}
			else y = temp;
		}
		catch (NumberFormatException ex) {
			IJ.showMessage("ERRORE - Y: numero non valido!");
		}
		
		yText.setText(""+y);
		
		return result;
	}
	
	
	
	/**
	 * Create the application.
	 */
	public Coder_() {
		initialize();
	}

	
	
	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frmCoder = new JFrame();
		frmCoder.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		frmCoder.setResizable(false);
		frmCoder.setTitle("Coder");
		frmCoder.setBounds(100, 100, 542, 600);
		frmCoder.getContentPane().setLayout(null);
		
		JPanel planesPanel = new JPanel();
		planesPanel.setLayout(null);
		planesPanel.setBorder(new TitledBorder(null, "Piani colore", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		planesPanel.setBounds(10, 11, 254, 118);
		frmCoder.getContentPane().add(planesPanel);
		
		redCBox = new JCheckBox("Red");
		redCBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (redCBox.isSelected()) {
					red1RBox.setEnabled(true);
					red2RBox.setEnabled(true);
				}
				else {
					red1RBox.setEnabled(false);
					red2RBox.setEnabled(false);
				}
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		redCBox.setBounds(6, 17, 70, 23);
		planesPanel.add(redCBox);
		
		greenCBox = new JCheckBox("Green");
		greenCBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (greenCBox.isSelected()) {
					green1RBox.setEnabled(true);
					green2RBox.setEnabled(true);
				}
				else {
					green1RBox.setEnabled(false);
					green2RBox.setEnabled(false);
				}
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		greenCBox.setBounds(6, 43, 70, 23);
		planesPanel.add(greenCBox);
		
		blueCBox = new JCheckBox("Blue");
		blueCBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (blueCBox.isSelected()) {
					blue1RBox.setEnabled(true);
					blue2RBox.setEnabled(true);
				}
				else {
					blue1RBox.setEnabled(false);
					blue2RBox.setEnabled(false);
				}
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		blueCBox.setBounds(6, 69, 70, 23);
		planesPanel.add(blueCBox);
		
		red1RBox = new JRadioButton("1 bit");
		red1RBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				red1RBox.setSelected(true);
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		redGroup.add(red1RBox);
		red1RBox.setSelected(true);
		red1RBox.setEnabled(false);
		red1RBox.setBounds(78, 17, 70, 23);
		planesPanel.add(red1RBox);
		
		red2RBox = new JRadioButton("2 bit");
		red2RBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				red2RBox.setSelected(true);
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		redGroup.add(red2RBox);
		red2RBox.setEnabled(false);
		red2RBox.setBounds(152, 17, 70, 23);
		planesPanel.add(red2RBox);
		
		green1RBox = new JRadioButton("1 bit");
		green1RBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				green1RBox.setSelected(true);
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		greenGroup.add(green1RBox);
		green1RBox.setSelected(true);
		green1RBox.setEnabled(false);
		green1RBox.setBounds(78, 43, 70, 23);
		planesPanel.add(green1RBox);
		
		green2RBox = new JRadioButton("2 bit");
		green2RBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				green2RBox.setSelected(true);
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		greenGroup.add(green2RBox);
		green2RBox.setEnabled(false);
		green2RBox.setBounds(152, 43, 70, 23);
		planesPanel.add(green2RBox);
		
		blue1RBox = new JRadioButton("1 bit");
		blue1RBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				blue1RBox.setSelected(true);
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		blueGroup.add(blue1RBox);
		blue1RBox.setSelected(true);
		blue1RBox.setEnabled(false);
		blue1RBox.setBounds(78, 69, 70, 23);
		planesPanel.add(blue1RBox);
		
		blue2RBox = new JRadioButton("2 bit");
		blue2RBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				blue2RBox.setSelected(true);
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		blueGroup.add(blue2RBox);
		blue2RBox.setEnabled(false);
		blue2RBox.setBounds(152, 69, 70, 23);
		planesPanel.add(blue2RBox);
		
		JPanel pixelPanel = new JPanel();
		pixelPanel.setLayout(null);
		pixelPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Pixel iniziale", TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 0, 0)));
		pixelPanel.setBounds(275, 11, 254, 118);
		frmCoder.getContentPane().add(pixelPanel);
		
		daLabel = new JLabel("Da");
		daLabel.setBounds(10, 22, 234, 14);
		pixelPanel.add(daLabel);
		
		aLabel = new JLabel("A");
		aLabel.setBounds(10, 36, 234, 14);
		pixelPanel.add(aLabel);
		
		JLabel xLabel = new JLabel("X");
		xLabel.setBounds(10, 61, 15, 14);
		pixelPanel.add(xLabel);
		
		JLabel yLabel = new JLabel("Y");
		yLabel.setBounds(10, 86, 15, 14);
		pixelPanel.add(yLabel);
		
		xText = new JTextField();
		xText.setText("0");
		xText.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		xText.setColumns(10);
		xText.setBounds(26, 58, 86, 20);
		pixelPanel.add(xText);
		
		yText = new JTextField();
		yText.setText("0");
		yText.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		yText.setColumns(10);
		yText.setBounds(26, 83, 86, 20);
		pixelPanel.add(yText);
		
		JPanel othersPanel = new JPanel();
		othersPanel.setBorder(new TitledBorder(null, "Altre opzioni", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		othersPanel.setBounds(10, 140, 518, 71);
		othersPanel.setLayout(null);
		frmCoder.getContentPane().add(othersPanel);
				
		cifraturaCBox = new JCheckBox("Cifratura messaggio con password");
		cifraturaCBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (cifraturaCBox.isSelected()) {
					passwordField.setEditable(true);
				}
				else {
					passwordField.setEditable(false);
				}
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		cifraturaCBox.setBounds(6, 14, 254, 23);
		othersPanel.add(cifraturaCBox);
		
		JLabel saltoLabel = new JLabel("Salto pixel");
		saltoLabel.setBounds(266, 18, 82, 14);
		othersPanel.add(saltoLabel);
		
		saltoBox = new JComboBox();
		//setta i valori della comboBox nel range 0-255
		String[] numSalto = new String[256];
		for (int i=0; i<numSalto.length; i++) numSalto[i] = ""+i;
		saltoBox.setModel(new DefaultComboBoxModel(numSalto));
		saltoBox.setSelectedIndex(0);
		saltoBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		saltoBox.setBounds(333, 15, 60, 20);
		othersPanel.add(saltoBox);
		
		JLabel passwordLabel = new JLabel("Password:");
		passwordLabel.setBounds(10, 43, 74, 14);
		othersPanel.add(passwordLabel);
		
		passwordField = new JPasswordField();
		passwordField.setEditable(false);
		passwordField.setBounds(94, 40, 158, 20);
		othersPanel.add(passwordField);
		
		keyCBox = new JCheckBox("Inserisci chiave steganografica");
		keyCBox.setFont(new Font("Tahoma", Font.BOLD, 11));
		keyCBox.setBounds(262, 39, 250, 23);
		othersPanel.add(keyCBox);
		keyCBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				calcPixelLimits();
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		
		JPanel msgPanel = new JPanel();
		msgPanel.setBorder(new TitledBorder(null, "Messaggio", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		msgPanel.setBounds(10, 222, 518, 305);
		msgPanel.setLayout(null);
		frmCoder.getContentPane().add(msgPanel);
				
		typeBox = new JComboBox();
		typeBox.setModel(new DefaultComboBoxModel(new String[] {"Testo", "File"}));
		typeBox.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (typeBox.getSelectedIndex() == 0) { //testo
					textArea.setText("");
					textArea.setEditable(true);
					browseButton.setEnabled(false);
				}
				else  {	//file
					textArea.setText("");
					textArea.setEditable(false);
					browseButton.setEnabled(true);
				}
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		typeBox.setBounds(10, 21, 60, 20);
		msgPanel.add(typeBox);
		
		browseButton = new JButton("Browse");
		browseButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				final JFileChooser fc = new JFileChooser();
				int returnVal = fc.showOpenDialog(null);
		        if (returnVal == JFileChooser.APPROVE_OPTION) {
		            file = fc.getSelectedFile();
		            textArea.setText("\""+file.getAbsolutePath()+"\"");
		        }
			}
		});
		browseButton.setBounds(419, 20, 89, 23);
		msgPanel.add(browseButton);
		browseButton.setEnabled(false);
		
		JScrollPane scrollPane = new JScrollPane();
		scrollPane.setBounds(10, 52, 498, 242);
		msgPanel.add(scrollPane);
		
		textArea = new JTextArea();
		scrollPane.setViewportView(textArea);
		
		JButton maxButton = new JButton("Max");
		maxButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setX(); //richiama anche setY()
				calcMax();
			}
		});
		maxButton.setBounds(10, 538, 89, 23);
		frmCoder.getContentPane().add(maxButton);
		
		maxLabel = new JLabel("Max caratteri: 0");
		maxLabel.setBounds(109, 542, 295, 14);
		frmCoder.getContentPane().add(maxLabel);
		
		JButton codeButton = new JButton("Code");
		codeButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				startCode();
			}
		});
		codeButton.setBounds(440, 538, 89, 23);
		frmCoder.getContentPane().add(codeButton);
	}



	public void run(ImageProcessor ip) {
		h = ip.getHeight(); //altezza immagine
		w = ip.getWidth(); //larghezza immagine
		this.ip = ip;
		calcPixelLimits();
		setX(); //richiama anche setY()
		
		frmCoder.setTitle("Coder - "+imp.getTitle());
		frmCoder.setVisible(true);		
	}



	public int setup(String arg, ImagePlus imp) {
		this.imp = imp;
		return DOES_RGB;
	}
}
