#include "export_LUTs.h"

void Export_LUTs::export_LUTs(char* name_of_file) {

	std::ofstream fout(name_of_file);
	std::string model = name_of_file;

	unsigned int depth=0;
	
	for (std::list<Gate*>::iterator it = outputs.begin(); it != outputs.end(); ++it) {
		if ( depth < (*it)->get_depth_of_lut())	{
			depth = (*it)->get_depth_of_lut();
		}
	}
	size_t pos = model.find_last_of(".");
	model = model.substr(0,pos);

	fout << ".model " << model.c_str() << std::endl;
	fout << "# Result of mapping:\n";
	fout << "# ==================\n";
	fout << "# Number of luts: " << luts.size() << "\n";
	fout << "# Depth of critical path: " << depth << "\n";
	fout << "\n";
	fout << ".inputs ";
	for (std::list<Gate*>::iterator it = inputs.begin(); it != inputs.end(); ++it) {
		fout << (*it)->get_name().c_str() << " ";
	}
	fout << std::endl<<std::endl;

	fout << ".outputs ";
	for (std::list<Gate*>::iterator it = outputs.begin(); it != outputs.end(); ++it) {
		fout << (*it)->get_name().c_str() << " ";
	}
	fout << std::endl;

	
	for (std::list<Lut*>::iterator it = luts.begin(); it != luts.end(); ++it) {
		fout << "\n.names ";
		for (std::list<Gate*>::iterator it_vstupy = (*it)->names_inputs.begin(); it_vstupy != (*it)->names_inputs.end(); ++it_vstupy) {
			fout << (*it_vstupy)->get_name().c_str() << " ";
		}
		fout << (*it)->name.c_str();
		fout << std::endl;
		for (True_table::iterator it_row = (*it)->true_table->begin(); it_row != (*it)->true_table->end(); ++it_row) {
			for (std::list<int>::iterator it_vstupy = (*it)->inputs.begin(); it_vstupy != (*it)->inputs.end(); ++it_vstupy) {
				std::map<int,int>::const_iterator result = (*it_row)->find(*it_vstupy);
				if (result == (*it_row)->end()) {
					fout << "-";
				}
				else
				{
					fout << (*result).second;
				}
				
			}

			fout << " 1" << std::endl;
		}
	}

	
	fout << ".end" << std::endl;
	fout.close();

}