#include <iostream>
#include <cstdlib>
#include <fstream>
#include <string>

int main( int argc, char **argv ) {

	if( argc != 2 ) {
		std::cout << "Usage: " << argv[ 0 ] << " <input.emm>" << std::endl;
	}

	std::fstream file( argv[ 1 ], std::ios::in );
	if( !file.is_open() ) {
		std::cerr << "Error while opening file" << std::endl;
		exit( 1 );
	}

	std::string fn( argv[ 1 ] );
	std::string line;
	getline( file, line );

	std::ofstream mat( (fn + ".mtx").c_str() );
	mat << "%%MatrixMarket " << line.substr( 24 ) << std::endl;
	getline( file, line );
	while( line.substr( 0, 1 ) == "%" ) {
		mat << line << std::endl;
		getline( file, line );
	}
	mat << line << std::endl;
	const unsigned long int P = strtol( line.substr( line.find_last_of( ' ' ) ).c_str(), NULL, 10 );
	for( unsigned long int s = 0; s < P; ++s ) {
		getline( file, line );
		const unsigned long int curindex = strtoul( line.c_str(), NULL, 10 );
		mat << (curindex-1) << std::endl;
	}
	getline( file, line );	
	while( line.substr( 0, 1 ) != "%" ) {
		mat << line << std::endl;
		getline( file, line );
	}
	mat.close();

	while( line.substr( 0, 14 ) != "%%Input-vector" )
		getline( file, line );

	std::ofstream v( (fn + ".u").c_str() );
	getline( file, line );
	while( line.substr( 0, 1 ) != "%" ) {
		v << line << std::endl;
		getline( file, line );
	}
	v.close();

	while( line.substr( 0, 15 ) != "%%Output-vector" )
		getline( file, line );

	std::ofstream u( (fn + ".v").c_str() );
	getline( file, line );
	while( line.substr( 0, 1 ) != "%" ) {
		u << line << std::endl;
		getline( file, line );
	}
	u.close();

	file.close();
	return 0;
}

