
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class ReadTemplate {

	private static char[] character = {'a','b','c','d','A','B','C','D'};
	//สร้าง BufferedImage ให้เป็นอาร์เรย์
	private BufferedImage[] tmpImg;
	private BufferedImage inputImg;
	//สร้าง File ให้เป็นอาร์เรย์
	private File[] fileImg;
	//สร้าง อาเรย์สำหรับเก็บความกว้าง
	private int[] width;
	//สร้าง อาเรย์สำหรับเก็บความสูง
	private int[] height;
	//ตัวแปรสำหรับเก็บจำนวนตัวอักษร
	private int amount;
	
	public ReadTemplate(){
		 amount = 8;
		 tmpImg = new BufferedImage[amount];
		 fileImg = new File[amount];
		 width = new int[amount];
		 height = new int [amount];
		 
		 for(int i=1;i<=amount;i++){
			 try {
					// Read from a file
					fileImg[i-1] = new File(i+".gif");
					//อ่านไฟล์ลงอาร์เรย์ของ BufferedImage
					tmpImg[i-1] = ImageIO.read(fileImg[i-1]);
					//เก็บค่า width ลงอาร์เรย์
					width[i-1] = tmpImg[i-1].getWidth();
					//เก็บค่า height ลงอาร์เรย์
					height[i-1] = tmpImg[i-1].getHeight();
					
					System.out.println(fileImg[i-1].getName()+" , "+character[i-1]+" ,Width: "+
							+width[i-1]+"  Height: "+height[i-1]);
				} catch (IOException e) { 

					System.err.println("Cannot open the file.");
				}
		 }
	}
	
	public  void readInput(){
		int w;
		int h;
		try {

			// Read from a file
			File file = new File("input_char.gif");
			inputImg = ImageIO.read(file);
		} catch (IOException e) {

			System.err.println("Cannot open the file.");
		}
		
		w = inputImg.getWidth();
		h = inputImg.getHeight();
		
		System.out.println("");
		//เปรียบเทียบความกว้าง สูงระหว่างเทมเพลต กับ input เพื่อกรองเฉพาะที่กว้างสูงตรงกัน
		for(int i=0;i<amount;i++){
			if(width[i]==w && height[i]==h){
				System.out.println("Match with :"+character[i]);
				System.out.println(templateMatch(i,w,h));
			}
		}
		
	}
	
	public int templateMatch(int ii,int w,int h){
		int count = 0;
		int result;

		//เปรียบเทียบ template จากสูตร sum square different
		for(int i=0;i<w;i++)
			for(int j=0;j<h;j++){
				count += Math.pow(tmpImg[ii].getRGB(i,j)-inputImg.getRGB(i,j),2);
				
			}
		
		
		return count;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ReadTemplate rt = new ReadTemplate();
		rt.readInput();
	}

}
