
package lab1.resources;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

public class PatternsIO
{
public static SetOfPatterns ReadFromFile(String fileName, java.util.ArrayList<String> classLabels) throws IOException
{
SetOfPatterns set = new SetOfPatterns();
BufferedReader rd=new BufferedReader(new FileReader(fileName));
try
{
// read n, m, p 
String[] items = rd.readLine().trim().split("[,]", -1);
int n = Integer.parseInt(items[0]);
int p = Integer.parseInt(items[1]);
int m = Integer.parseInt(items[2]);
// read m labels for the m classes 
String[] labels = rd.readLine().split("[,]", -1);
 classLabels= new java.util.ArrayList<String>();
for (int i = 0; i < labels.length; i++)
{
 classLabels.add(labels[i]);
}
// read n patterns 
for (int i = 0; i < n; i++)
{
 items = rd.readLine().split("[,]", -1);
Pattern pattern = new Pattern(p);
for (int j = 0; j < p; j++)
{
 pattern.setItem(j, Double.parseDouble(items[j]));
 
}
 pattern.setClassIndex(Integer.parseInt(items[p]));
 set.Add(pattern);
}

}
finally
{
if (rd != null)
{
rd.close();
}
}
return set;
}
public static void WriteToFile(SetOfPatterns set, java.util.ArrayList<String> classLabels, String fileName) throws IOException
{
	BufferedWriter out = new BufferedWriter(new FileWriter(fileName));
	try
	{
	
		// write n, m, p 
		out.write(" "+set.getCount()+" "+ set.getItem(0).getCount()+" "+classLabels.size());
                out.newLine();
		// write m labels 
		for (int i = 0; i < classLabels.size(); i++)
		{
                   
			out.write( classLabels.get(i));
                        if(i == classLabels.size() - 1)
                            out.write(" ");
                        else
                            out.write(",");
		     out.newLine();
                }
		out.write("");
		// write the patterns 
		for (int i = 0; i < set.getCount(); i++)
		{
			for (int j = 0; j < set.getItem(i).getCount(); j++)
			{
				out.write(" "+set.getItem(i).getItem(j));
			}
                        
			out.write(" "+ set.getItem(i).getClassIndex());
                        out.newLine();
		}
	}
	finally
	{
		if (out != null)
		{
			out.close();
		}
	}
}
}