package main;

import fr.lip6.classifier.SMOSVM;
import hypothesis_validation.HoG_Functions;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.ObjectInputStream;
import java.io.PrintStream;
import java.util.ArrayList;

import descriptors.hog;
import parameters.detection_arguments;
import preprocessing.Parser;
import preprocessing.Util;

public class Score_Signature {
		
	public static void main(String[] args) throws IOException {
			
		String image_list = args[0];
		
		String detection_file = args[1];
		
		String out_file = args[2];
		
		detection_arguments detection_parameters = new detection_arguments(detection_file);
		
		ArrayList<Double> mean = new ArrayList<Double>();
		
		ArrayList<Double> deviation = new ArrayList<Double>();
		
		HoG_Functions.read_hog_vectors (mean, deviation, detection_parameters.hog_normalization);

		
		SMOSVM<double[]> cls = null;
		try {
    		ObjectInputStream obj = new ObjectInputStream(new FileInputStream(detection_parameters.hog));
    	    cls = (SMOSVM<double[]>) obj.readObject();
    	    obj.close();
    	}
    	catch (Exception e){
    		e.printStackTrace();
    	}
    	
    	Parser parser = new Parser();

		LineNumberReader list = parser.Open_File (image_list);
		
		int frame = 0;
		
		ArrayList<Double> array = new ArrayList<Double>();
		
		while(true) {
			
			/*Reading the image*/
			String image_name = Util.Get_Name (list);
			
			BufferedImage in_image = Util.Get_Image (image_name);

			if (in_image == null) { break; }
			
			double v = HoG_Functions.Get_HoG_Score (in_image, mean, deviation, cls, detection_parameters);
			
			array.add(v);
					
			frame++;
		}
		
		//double[] weigths = {0.1, 0.2, 0.3, 0.4};
			
		double[] weigths = {0.1, 0.15, 0.2, 0.25, 0.3};
		
        double[] weighted_array = new double[array.size()]; 
        
        int weights_size = weigths.length-1;
        
        for (int i = 0; i < array.size(); i++) {
        	if (i < weights_size) {
        		weighted_array[i] = array.get(i);
        	}
        	else {
        	    weighted_array[i] = 
        	    	                array.get(i - 3)*weigths[weights_size - 4] +
        	    	                array.get(i - 3)*weigths[weights_size - 3] + 
        	                        array.get(i - 2)*weigths[weights_size - 2] +
        	                        array.get(i - 1)*weigths[weights_size - 1] +
        	                        array.get(i - 0)*weigths[weights_size - 0];
        	}
		}

		try {
			
			FileOutputStream file = new FileOutputStream(out_file); 

			PrintStream out = new PrintStream(file);

			for (int i = 0; i < array.size(); i++) {
				out.printf("%d %f %f\n", i, array.get(i), weighted_array[i]);
			}
			
			out.close();
		}
		catch (IOException e) {
			System.err.println ("Error to wrote the output file\n");
			e.printStackTrace();
		} 
	}
}
