package lab5;

import java.io.BufferedReader;
import java.io.IOException;

import martin.IO;

/**
 * exercise 2
 * @author martin
 *Écrivez un programme qui créera un tableau de statistiques montrant la fréquence de parution d’un
*caractère dans un fichier. Faîtes-le avec un tableau en utilisant le code ASCII comme indice des 255
*caractères possibles. Il faut afficher à la sortie tous les caractères rencontrés en indiquant le nombre
*d’occurrences et le pourcentage d’occurrences selon le nb total de caractères.
 */
public class StatistiqueFichierBinaire {
	/*properties*/
	private int [] _compte;
	private int _autre;
	private int _qty;

	/*constructor*/
	public StatistiqueFichierBinaire(int nb){
		_compte = new int[nb];
		_qty = 0;
		for (int i=0;i<nb;i++)
			_compte[i] = 0;
		_autre=0;
	}

	/*mutator*/
	public void add(int data){
		if (data >= _compte.length)
			_autre++;
		else
			_compte[data]++;
		_qty++;
	}

	/*obj method*/
	public String toString(){
		String tmp = new String("Statistique fichier binaire\n");
		for (int i=0;i<_compte.length;i++)
			if (_compte[i]>0)
				tmp = tmp + "char # " + i +
								   (i<255&&i>32?" (" + (char)i + ") "  : ' ')+
						           ((double)_compte[i]/_qty*100) + "%" + "\n";
		tmp += "autre : " + ((double)_autre/_qty*100) + "%";
		tmp += "nombre de caractere = "+_qty;
		return tmp;
	}

	//main
	public static void main(String [] args) throws IOException{
		//initialisation
		String fichierClass = "LecteurFichierBinaire.class";
		BufferedReader lire = IO.openReader(fichierClass);
		StatistiqueFichierBinaire stat = new StatistiqueFichierBinaire(256);

		//boucle
		while(lire.ready()){
			int data = lire.read();
			stat.add(data);
		}
		lire.close();

		//affichage
		System.out.print(stat.toString());

	}
}
