import ij.*;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.plugin.*;
import ij.plugin.frame.*;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JButton;
import javax.swing.JOptionPane;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedList;
import java.awt.Color;
import javax.swing.JTable;
import java.awt.Font;
import javax.swing.table.DefaultTableModel;
import javax.swing.border.EtchedBorder;
import javax.swing.JTextArea;
import javax.swing.SwingConstants;
import javax.swing.JScrollPane;
import java.awt.Choice;

public class DQT_Extract extends JFrame implements PlugIn {
	File chosen; //File per la gestione di file/directory selezionati
	String pathChosen; //Stringa che serve a indicare dove generare l'output (il report)
	JLabel lblChosenPath; //Label che indica il path assoluto di file/directory selezionati
	final private static String pathDB = "plugins\\CF\\DQTDBCoded.dmi"; //path assoluto del database di tabelle e device
	static LinkedList<DQTable> lista;
	private DQTable[] dqtList;
	
	private JPanel contentPane;
	private JTable table_1;
	private JTable table_2;
	private JLabel lbllumtab;
	private JLabel lblchrtab;
	private JLabel lblHELPbrowse;
	private JLabel lblCurrentFile;
	private JLabel lblDeviceMatching;
	private JLabel lblFeedbackReport;
	private Choice choice;
	private JButton btnGAR;
	private JButton btnGSR;
	private JButton btnAddThisDqt;
	private JScrollPane scrollPane;
	private JTextArea txtarDevMat;
	
	private ImagePlus imp;
	
	/**
	 * Launch the application.
	 */
	public void run(String arg) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					DQT_Extract frame = new DQT_Extract();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public DQT_Extract() { //costruttore
		setTitle("DQT Extract Tool");
		
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 609, 365);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		// -------------------------------------****** LABLE CHOSEN
		lblChosenPath = new JLabel("No file or directory selected.");
		lblChosenPath.setBackground(Color.WHITE);
		lblChosenPath.setBounds(139, 45, 334, 23);
		contentPane.add(lblChosenPath);

		//System.out.println("- TEST -: Dimensione contentPane = "+contentPane.getSize());

		// -------------------------------------****** BUTTON BROWSE
		JButton btnApriFile = new JButton("Browse");
		btnApriFile.addActionListener(new ActionListener() 
		{
			public void actionPerformed(ActionEvent arg0) 
			{
				JFileChooser chooser = new JFileChooser();
				FileNameExtensionFilter filter = new FileNameExtensionFilter(
						"JPG", "jpg");
				chooser.setFileFilter(filter);
				chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
				int returnVal = chooser.showOpenDialog(getParent());
				if(returnVal == JFileChooser.APPROVE_OPTION) 
				{
					chosen = chooser.getSelectedFile();
					//System.out.println("- TEST -: You chose to open this file: " +
					//		chosen.getAbsolutePath());

					lblChosenPath.setVisible(true);
					if (chosen.isDirectory())
					{
						pathChosen=chosen.getAbsolutePath();
						lblChosenPath.setText(pathChosen);
					}
					else
					{
						pathChosen=chosen.getParentFile().getAbsolutePath();
						lblChosenPath.setText(chosen.getAbsolutePath());
					}
					
					lblHELPbrowse.setVisible(false);
					lblFeedbackReport.setVisible(false);
					
					File file = chosen;
					
					try 
					{
						DQTDBParser.parseFile(pathDB);

						if(file.isDirectory())
						{ //cartella - gestione lavoro batch (immagini multiple)
							File[] fileList = file.listFiles(new FilterJPG());
							dqtList = new DQTable[fileList.length];
							
							choice.removeAll();
							for(int i=0; i<fileList.length;i++)
							{
								choice.add(fileList[i].getName());
								dqtList[i] = DQTDBParser.parseImage(fileList[i]);
							}
							if(fileList.length==0)
							{ //cartella vuota
								txtarDevMat.setText("");
								btnGAR.setEnabled(false);
								btnGSR.setEnabled(false);
								btnAddThisDqt.setEnabled(false);
								lblChosenPath.setText(file.getAbsolutePath());
								choice.add("No image(s) in current directory");
								resetTable();
							}
							else
							{ //se la cartella non è vuota mostra l'analisi della prima imm .jpeg trovata
								btnGAR.setEnabled(true);
								btnGSR.setEnabled(true);
								btnAddThisDqt.setEnabled(true);
								compileTable(dqtList[0]);
								txtarDevMat.setText(dqtList[0].getDiscoveredDevices());
							}
						}
						else
						{ //immagine singola
							btnGAR.setEnabled(false);
							btnGSR.setEnabled(true);
							btnAddThisDqt.setEnabled(true);
							dqtList = new DQTable[1];
							dqtList[0] = DQTDBParser.parseImage(file);
							choice.removeAll();
							choice.add(file.getName());
							compileTable(dqtList[0]);
							txtarDevMat.setText(dqtList[0].getDiscoveredDevices());
							//System.out.println("- TEST -: Device: "+dqtList[0].getDiscoveredDevices());
						}
					} catch(IOException e){
						System.out.println("Errore I/O");
					}
					
				}				
			}
		});
		
		// -------------------------------------****** LABLE CURRENT FILE
		lblCurrentFile = new JLabel("Current File/Directory:");
		lblCurrentFile.setHorizontalAlignment(SwingConstants.RIGHT);
		lblCurrentFile.setBounds(0, 45, 129, 23);
		contentPane.add(lblCurrentFile);
		btnApriFile.setBounds(40, 11, 89, 23);
		contentPane.add(btnApriFile);

		// -------------------------------------****** TABLE LUMINANCE
		table_1 = new JTable();
		table_1.setShowGrid(false);
		table_1.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		table_1.setFont(new Font("Tahoma", Font.PLAIN, 10));
		table_1.setModel(new DefaultTableModel(
				new Object[][] {
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
				},
				new String[] {
						"New column", "New column", "New column", "New column", "New column", "New column", "New column", "New column"
				}
		) {
			boolean[] columnEditables = new boolean[] {
					false, false, false, false, false, false, false, false};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		table_1.getColumnModel().getColumn(0).setPreferredWidth(15);
		table_1.getColumnModel().getColumn(1).setPreferredWidth(15);
		table_1.getColumnModel().getColumn(2).setPreferredWidth(15);
		table_1.getColumnModel().getColumn(3).setPreferredWidth(15);
		table_1.getColumnModel().getColumn(4).setPreferredWidth(15);
		table_1.getColumnModel().getColumn(5).setPreferredWidth(15);
		table_1.getColumnModel().getColumn(6).setPreferredWidth(15);
		table_1.getColumnModel().getColumn(7).setPreferredWidth(15);
		table_1.setBounds(10, 179, 163, 128);
		contentPane.add(table_1);

		// -------------------------------------****** TABLE CHROMINANCE
		table_2 = new JTable();
		table_2.setShowGrid(false);
		table_2.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		table_2.setFont(new Font("Tahoma", Font.PLAIN, 10));
		table_2.setModel(new DefaultTableModel(
				new Object[][] {
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
						{null, null, null, null, null, null, null, null},
				},
				new String[] {
						"New column", "New column", "New column", "New column", "New column", "New column", "New column", "New column"
				}
		) {
			boolean[] columnEditables = new boolean[] {
					false, false, false, false, false, false, false, false
			};
			public boolean isCellEditable(int row, int column) {
				return columnEditables[column];
			}
		});
		table_2.getColumnModel().getColumn(0).setPreferredWidth(15);
		table_2.getColumnModel().getColumn(1).setPreferredWidth(15);
		table_2.getColumnModel().getColumn(2).setPreferredWidth(15);
		table_2.getColumnModel().getColumn(3).setPreferredWidth(15);
		table_2.getColumnModel().getColumn(4).setPreferredWidth(15);
		table_2.getColumnModel().getColumn(5).setPreferredWidth(15);
		table_2.getColumnModel().getColumn(6).setPreferredWidth(15);
		table_2.getColumnModel().getColumn(7).setPreferredWidth(15);
		table_2.setBounds(190, 179, 163, 128);
		contentPane.add(table_2);

		// -------------------------------------****** LABLE LUMINANCE
		lbllumtab = new JLabel("DQT Luminance");
		lbllumtab.setHorizontalAlignment(SwingConstants.CENTER);
		lbllumtab.setBounds(10, 153, 163, 23);
		contentPane.add(lbllumtab);

		// -------------------------------------****** LABLE CHROMINANCE
		lblchrtab = new JLabel("DQT Chrominance");
		lblchrtab.setHorizontalAlignment(SwingConstants.CENTER);
		lblchrtab.setBounds(190, 153, 163, 23);
		contentPane.add(lblchrtab);		
		
		// -------------------------------------****** LABLE DEVICE MATCHING
		lblDeviceMatching = new JLabel("Device(s) matching:");
		lblDeviceMatching.setHorizontalAlignment(SwingConstants.CENTER);
		lblDeviceMatching.setBounds(393, 153, 190, 23);
		contentPane.add(lblDeviceMatching);
		
		// -------------------------------------****** LABLE HELP BROWSE
		lblHELPbrowse = new JLabel("<=== Tip: Select new .jpg image or a directory");
		lblHELPbrowse.setBackground(Color.WHITE);
		lblHELPbrowse.setBounds(139, 11, 334, 23);
		contentPane.add(lblHELPbrowse);
		
		// -------------------------------------****** CHOICE
		choice = new Choice();
		choice.setBounds(25, 74, 286, 20);
		choice.addItemListener(new myEventsList());
		contentPane.add(choice);
		
		// -------------------------------------****** BUTTON GAR
		btnGAR = new JButton("Generate All Reports");
		btnGAR.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0)
			{
				try {
					int size = dqtList.length;
					
					for(int i=0; i<size; i++)
					{
						DQTDBParser.printReport(choice.getItem(i), dqtList[i], pathChosen);
					}
				} catch(IOException e){
					e.printStackTrace();
				}
				lblFeedbackReport.setVisible(true);
			}
		});
		btnGAR.setEnabled(false);
		btnGAR.setBounds(393, 108, 193, 23);
		contentPane.add(btnGAR);
		
		// -------------------------------------****** BUTTON GSR
		btnGSR = new JButton("Generate Selected Report");
		btnGSR.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0)
			{
				try {
					DQTDBParser.printReport(choice.getSelectedItem(), dqtList[choice.getSelectedIndex()], pathChosen);
				} catch(IOException e){
					e.printStackTrace();
				}
				lblFeedbackReport.setVisible(true);
			}
		});
		btnGSR.setEnabled(false);
		btnGSR.setBounds(393, 74, 193, 23);
		contentPane.add(btnGSR);
		
		// -------------------------------------****** LABEL FEEDBACKREPORT
		lblFeedbackReport = new JLabel("Success: report(s) created.");
		lblFeedbackReport.setHorizontalAlignment(SwingConstants.CENTER);
		lblFeedbackReport.setVisible(false);
		lblFeedbackReport.setBounds(64, 100, 215, 23);
		contentPane.add(lblFeedbackReport);
		
		// -------------------------------------****** SCROLLPANE
		scrollPane = new JScrollPane();
		scrollPane.setBounds(393, 179, 190, 128);
		contentPane.add(scrollPane);
		
		// -------------------------------------****** JTEXTPANE
		txtarDevMat = new JTextArea();
		txtarDevMat.setFont(new Font("Monospaced", Font.PLAIN, 11));
		txtarDevMat.setEditable(false);
		scrollPane.setViewportView(txtarDevMat);		
		
		// -------------------------------------****** BUTTON ABOUT
		JButton btnAbout = new JButton("About");
		btnAbout.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				JOptionPane.showMessageDialog(null, 
						"Developers Allegra Dario, Milotta Filippo\r\n\r\n" +
						"        Advisor Professor Battiato S.\r\n\r\n"+
						"                University of Catania\r\n\r\n",
						"About this ImageJ plugin",
						JOptionPane.INFORMATION_MESSAGE);
			}
		});
		btnAbout.setBounds(494, 11, 89, 23);
		contentPane.add(btnAbout);
		
		// -------------------------------------****** BUTTON ADD
		btnAddThisDqt = new JButton("Add this DQT");
		btnAddThisDqt.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) 
			{
				try
				{
					String name;
					name=JOptionPane.showInputDialog("New device name:");
					if(name.length()==0)
						name="Device Undefined";
					addDB(name,dqtList[choice.getSelectedIndex()]);
				}
				catch(IOException e)
				{
					e.printStackTrace();
				}
			}
		});
		btnAddThisDqt.setBounds(262, 108, 116, 23);
		contentPane.add(btnAddThisDqt);
		btnAddThisDqt.setEnabled(false);		
		
		// -------------------------------------****** GESTIONE POSSIBILE IMMAGINE APERTA DI IMAGEJ
		imp = WindowManager.getCurrentImage();
		if (imp == null){
			IJ.showStatus("No already opened image. Select one from browse button.");
			lblChosenPath.setText("No already opened image(s) on ImageJ");
		} else {
			pathChosen = imp.getOriginalFileInfo().directory+""+imp.getTitle();
			IJ.showStatus(pathChosen);
			lblChosenPath.setText(pathChosen);
			chosen = new File(pathChosen);
			pathChosen = chosen.getParentFile().getAbsolutePath();
			try {
				DQTDBParser.parseFile(pathDB);

				btnGAR.setEnabled(false);
				btnGSR.setEnabled(true);
				btnAddThisDqt.setEnabled(true);
				dqtList = new DQTable[1];
				dqtList[0] = DQTDBParser.parseImage(chosen);
				choice.removeAll();
				choice.add(chosen.getName());
				compileTable(dqtList[0]);
				txtarDevMat.setText(dqtList[0].getDiscoveredDevices());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	private void compileTable(DQTable ut)
	{ //riempie le tabelle del plugin con i valori dell'immagine selezionata
		int[][] LTable = ut.getLTable();
		int[][] CTable = ut.getCTable();

		for(int x=0; x<8; x++)
		{
			for(int y=0; y<8; y++)
			{
				table_1.setValueAt(new Integer(LTable[x][y]), x, y);
				table_2.setValueAt(new Integer(CTable[x][y]), x, y);
			}
		}
	}
	private void resetTable()
	{ //resetta le tabelle del plugin eliminando i valori della precedente immagine selezionata
		for(int x=0; x<8; x++)
		{
			for(int y=0; y<8; y++)
			{
				table_1.setValueAt(null, x, y);
				table_2.setValueAt(null, x, y);
			}
		}
	}
	
	public void addDB(String n, DQTable tab) //Aggiunge device-tabelle al DB
	throws IOException
	{
		FileOutputStream out=null;
		PrintWriter outPrint;
	
		try
		{
			out = new FileOutputStream(pathDB, true);
			outPrint = new PrintWriter(out);
			
			out.write(0);
			outPrint.print(n);
			outPrint.flush();
			out.write(0);
			out.write(tab.getLMean());
			out.write(0);
			out.write(tab.getCMean());
			out.write(0);
			for(int i=0; i<64; i++)
			{
				out.write(tab.getLTableS()[i]);
			}
			out.write(0);
			for(int i=0; i<64; i++)
			{
				out.write(tab.getCTableS()[i]);
			}
			outPrint.print("\r\n");
			outPrint.flush();
			
			DQTable tmp=dqtList[choice.getSelectedIndex()];
			if(tmp.getDiscoveredDevices().equals("No Device matching"))
			{
				tmp.setDiscoveredDevices(n);				
			}
			else
			{
				tmp.setDiscoveredDevices(tmp.getDiscoveredDevices() + n);
			}
			txtarDevMat.setText(dqtList[choice.getSelectedIndex()].getDiscoveredDevices());
		} catch(IOException e) {
			e.printStackTrace();
		} finally {
			if(out!=null)	out.close();
		}
	}
	
	// -------------------------
	//	   CLASSE EventeList
	// -------------------------
	public class myEventsList implements ItemListener{
		public void itemStateChanged(ItemEvent e){
			compileTable(dqtList[choice.getSelectedIndex()]);
			txtarDevMat.setText(dqtList[choice.getSelectedIndex()].getDiscoveredDevices());
			lblFeedbackReport.setVisible(false);
		}
	}
}

// -------------------------
//		CLASSE DQTable
// -------------------------
class DQTable
{
	private int[] LTableS=new int[64]; //DQT Luminanza rappr. serpentina
	private int[] CTableS=new int[64]; //DQT Crominanza rappr. serpentina
	private int[][] LTable=new int[8][8]; //DQT Luminanza rappr. bidimensionale
	private int[][] CTable=new int[8][8]; //DQT Crominanza rappr. bidimensionale
	private int LMean; //Valore medio di DQT Luminanza per accelerare ricerca nel DB
	private int CMean; //Valore medio di DQT Crominanza per accelerare ricerca nel DB
	private String name; //Nome dell'immagine
	private String discoveredDevices = ""; //Possibili device associati alle DQT

	//vari marker dei metadati
	final int SOI=0xD8;
	final int EOI=0xD9;
	final int DQT=0xDB;
	final int SOS=0xDA;
	final int MARK=0xFF;
	final int NOTH=0x00;

	public DQTable(String n, int[][] L,int LM, int[][] C, int CM)
	{ //costruttore nel caso in cui possediamo le DQT in rappr. bidimensionale
		name=n;
		LTable=L;
		CTable=C;
		LMean=LM;
		CMean=CM;
		matrix2snake();
	}

	public DQTable(String n, int[] L,int LM, int[] C, int CM)
	{ //costruttore nel caso in cui possediamo le DQT in rappr. serpentina
		name=n;
		LTableS=L;
		CTableS=C;
		LMean=LM;
		CMean=CM;
		snake2matrix();
	}

	public DQTable(String path)
	{ //costruttore nel caso in cui possediamo solo il path assoluto dell'immagine
		FileInputStream in;
		int c=0;
		int sC=0;
		int d;

		try {
			in=new FileInputStream(path);

			boolean fl;
			while(c!=-1)
			{
				c=in.read();
				if(c==MARK)
				{
					c=in.read();
					switch (c)
					{
					case SOI:
					{
						sC++;
						break;
					}

					case NOTH:
					{
						break;
					}

					case DQT:
					{

						if(sC==1)
						{
							in.skip(1);
							d=in.read();
							in.skip(1);
							int i=0;
							while(i<64){
								LTableS[i]=in.read();
								i++;
							}

							if(d>100)
								in.skip(1);
							else
								in.skip(5);

							i=0;
							while(i<64){
								CTableS[i]=in.read();
								i++;
							}
							c=-1;	
						}

						break;
					}

					case SOS:
					{

						fl=true;
						while(fl)
						{
							while((c=in.read())!=MARK)
							{
							}
							if((c=in.read())==EOI)
								fl=false;
						}
						sC--;

						break;
					}

					default:
					{
						c=in.read();
						c=c*256+in.read();
						in.skip(c-2);
					}
					}
				}
			}
			
			in.close();
		} catch(Exception e) {
			e.printStackTrace();
		}

		snake2matrix();

		name = "unknown device";

		LMean = calculateMean(LTableS);
		CMean = calculateMean(CTableS);
	}

	private void snake2matrix()
	{ //genera la rappr. bidimensionale
		int i=0;
		int k=0;
		int h=0;

		while(h<8)
		{
			for(k=0;k<=h;k++)
			{
				LTable[h-k][k]=LTableS[i];
				CTable[h-k][k]=CTableS[i];
				i++;
			}		
			h++;

			for(k=0;k<=h;k++)
			{
				LTable[k][h-k]=LTableS[i];
				CTable[k][h-k]=CTableS[i];
				i++;
			}
			h++;
		}

		h-=2;

		while(i<63)
		{
			for(k=0;k<=h;k++)
			{
				LTable[7-k][7-h+k]=LTableS[i];
				CTable[7-k][7-h+k]=CTableS[i];
				//System.out.print(- TEST -: k+" "+h+" "+i+" ");
				i++;
			}
			h--;

			for(k=0;k<=h;k++)
			{
				LTable[7-h+k][7-k]=LTableS[i];
				CTable[7-h+k][7-k]=CTableS[i];
				//System.out.print(- TEST -: k+" "+h+" "+i+" ");
				i++;
			}
			h--;
		}
		LTable[7][7]=LTableS[63];
		CTable[7][7]=CTableS[63];
	}

	private void matrix2snake()
	{ //genera la rappr. serpentina
		int i=0;
		int k=0;
		int h=0;

		while(h<8)
		{
			for(k=0;k<=h;k++)
			{
				LTableS[i]=(char)LTable[h-k][k];
				CTableS[i]=(char)CTable[h-k][k];
				i++;
			}		
			h++;

			for(k=0;k<=h;k++)
			{
				LTableS[i]=(char)LTable[k][h-k];
				CTableS[i]=(char)CTable[k][h-k];
				i++;
			}
			h++;
		}

		h-=2;

		while(i<63)
		{
			for(k=0;k<=h;k++)
			{
				LTableS[i]=(char)LTable[7-k][7-h+k];
				CTableS[i]=(char)CTable[7-k][7-h+k];
				//System.out.print(- TEST -: k+" "+h+" "+i+" ");
				i++;
			}
			h--;

			for(k=0;k<=h;k++)
			{
				LTableS[i]=(char)LTable[7-h+k][7-k];
				CTableS[i]=(char)CTable[7-h+k][7-k];
				//System.out.print(- TEST -: k+" "+h+" "+i+" ");
				i++;
			}
			h--;
		}
		LTableS[63]=(char)LTable[7][7];
		CTableS[63]=(char)CTable[7][7];
	}

	public void printSnakes()
	{ //stampa entrambe le DQT in rappr. serpentina
		for(int i=0;i<64;i++)
		{
			System.out.print(LTableS[i]+" ");
		}

		System.out.println("");

		for(int i=0;i<64;i++)
		{
			System.out.print(CTableS[i]+" ");
		}

		System.out.println("");
	}

	public void printName()
	{ //stampa il nome dell'immagine
		System.out.println(name);
	}

	public void printTables()
	{ //stampa entrambe le DQT in rappr. bidimensionale
		for(int x=0;x<8;x++)
		{
			for(int y=0;y<8;y++)
			{
				System.out.print(LTable[x][y]+"\t");
			}
			System.out.println("");
		}

		System.out.println("");
		for(int x=0;x<8;x++)
		{
			for(int y=0;y<8;y++)
			{
				System.out.print(CTable[x][y]+"\t");
			}
			System.out.println("");
		}
	}

	public String Table2String()
	{ //genera una stringa contenente la rappr. bidimensionale di entrambe le DQT
		String R = "DQT Luminance:\r\n";
		for(int x=0;x<8;x++)
		{
			for(int y=0;y<8;y++)
			{
				R+=LTable[x][y]+"\t";
			}
			R+="\r\n";
		}

		R+="\r\nDQT Chrominance:\r\n";
		for(int x=0;x<8;x++)
		{
			for(int y=0;y<8;y++)
			{
				R+=CTable[x][y]+"\t";
			}
			R+="\r\n";
		}
		return R+"\r\n";
	}

	private int calculateMean(int[] Table)
	{ //calcola la media di una tabella
		int x = 0;
		for(int i=0; i<64; i++)
			x += Table[i];

		return (int)(x/64);
	}

	public int compareTo(DQTable X)
	{ //confronta due immagini in base alle rispettive medie di luminanza e crominanza e successivamente a entrambe le DQT
		if(X.getLMean()!=LMean) return -1;
		if(X.getCMean()!=CMean) return -1;

		//System.out.println("- TEST -: Device: "+name);
		int i=0;
		while(i<64)
		{
			if(X.getLTableS()[i]!=LTableS[i]) return -1;
			//System.out.println("- TEST -: X.getLTableS() ["+i+"] = "+(int)X.getLTableS()[i]+"LTableS ["+i+"] = "+(int)LTableS[i]);
			if(X.getCTableS()[i]!=CTableS[i]) return -1;
			i++;
		}

		return 0;
	}

	public int[] getLTableS() 
	{
		return LTableS;
	}

	public int[] getCTableS() 
	{
		return CTableS;
	}

	public int[][] getLTable() 
	{
		return LTable;
	}

	public int getLMean() 
	{
		return LMean;
	}

	public int getCMean() 
	{
		return CMean;
	}

	public int[][] getCTable() 
	{
		return CTable;
	}

	public String getName() {
		return name;
	}
	
	public String getDiscoveredDevices(){
		return discoveredDevices;
	}
	
	public void setDiscoveredDevices(String d){
		discoveredDevices = d;
	}

}

//-------------------------
//	   CLASSE DB_Parser
//-------------------------
class DQTDBParser {
	//final private static String pathDB = "DQTDBCoded.txt";
	static LinkedList<DQTable> lista;

	public static void parseFile(String stringaInput)
	throws IOException { //genera la struttura dati DQT-Devices a partire dal DB
		FileInputStream in = null;
		DQTable table;
		lista=new LinkedList<DQTable>();

		int LM, CM;
		int[] LA = new int[64];
		int[] CA = new int[64];

		try
		{
			in = new FileInputStream(stringaInput);

			String name="";
			int c;
			in.skip(1);
			while((c=in.read())!=-1)
			{
				name="";

				while((c!=0) && (c!=-1))
				{
					name+=(char)c;
					c=in.read();
				}

				LM = in.read();
				//System.out.println("- TEST -: LM = "+LM);

				in.skip(1);

				CM = in.read();
				//System.out.println("- TEST -: CM = "+CM);

				in.skip(1);

				int i=0;
				while(i<64){
					LA[i]=in.read();
					i++;
				}

				/*
				System.out.println("- TEST -: LA = ");
				for(int i=0; i<64; i++)
					System.out.print((int)LA[i]+" ");

				System.out.println("");
				 */
				in.skip(1);

				i=0;
				while(i<64){
					CA[i]=in.read();
					i++;
				}

				/*
				System.out.println("- TEST -: CA = ");
				for(int i=0; i<64; i++)
					System.out.print((int)CA[i]+" ");

				System.out.println("");
				 */

				in.skip(3);
				table=new DQTable(name,LA,LM,CA,CM);
				lista.addLast(table);
				LA=new int[64];
				CA=new int[64];
			}

		} catch(IOException e){
			System.out.println("Errore I/O");
		} finally {
			if (in!=null) in.close();
		}

		/*
		System.out.println("- TEST -: Scorrimento lista DQT_DB");
		for(DQTable dt:lista)
		{	dt.printName();
			dt.printTables();
		}
		 */
	}

	public static DQTable parseImage(File file)
	throws IOException { //genera la stringa contenente i device associabili all'immagini
		DQTable ut = new DQTable(file.getAbsolutePath());
		String deviceDiscovered = "";

		for(DQTable dt:lista)
		{	
			if(dt.compareTo(ut)==0)
			{
				//System.out.println("- TEST -: OK");
				deviceDiscovered += dt.getName()+"\r\n";
				//System.out.println("- TEST -: Device corrispondente: "+dt.getName());
			}
		}
		
		if(deviceDiscovered.length()==0)
			deviceDiscovered = "No Device matching";
		
		ut.setDiscoveredDevices(deviceDiscovered);
		
		//printReport(file.getAbsolutePath(), ut, deviceDiscovered);

		return ut;
	}

	public static void printReport(String imName, DQTable tab, String path)
	throws IOException { //genera il report di imName in path
		PrintWriter out = null;
		String found = tab.getDiscoveredDevices();
		
		try {
			out = new PrintWriter(new FileWriter(path+"\\report"+imName+".txt"));
			//System.out.println("- TEST -: "+path+"\\report"+imName+".txt");

			out.print("Image name: "+imName+"\r\n\r\n");
			
			out.print(tab.Table2String());

			if(found.length()!=0)
			{
				out.print("Device/s found:\r\n"+found);
			} else {
				out.print("Device not found in Database");	
			}
			out.flush();
		} catch (IOException e){
			e.printStackTrace();
		} finally {
			if (out != null) out.close();
		}
	}
}

//-------------------------
//     CLASSE FilterJPG
//-------------------------
class FilterJPG implements FilenameFilter
{
	String est1=".jpeg";
	String est2=".jpg";
	String est3=".JPEG";
	String est4=".Jpeg";
	String est5=".Jpg";
	String est6=".JPG";
	public boolean accept(File dir, String name)
	{
		if((name.endsWith(est1))||(name.endsWith(est2))||(name.endsWith(est3))
				||(name.endsWith(est4))||(name.endsWith(est5))||(name.endsWith(est6)))
			return true;
		return false;

	}
}
