#include <v_lib.h>
#include "../utils/math_u.h"

void
DumpThreeMatrices(file_t out,matrix_t *m1, matrix_t *m2,matrix_t *prod)
{
	/*
	u32_t i,j,k,m,n,p;
	u32_t lines;
	m=m1->rows;
	n=m1->cols;
	p=m2->cols;
	*/
	umDumpMatrix(out,m1,"M1=\n",NULL,NULL,"| ","  "," |\n",true);
	umDumpMatrix(out,m2,"M2=\n",NULL,NULL,"| ","  "," |\n",true);
	umDumpMatrix(out,prod,"M1 * M2=\n",NULL,NULL,"| ","  "," |\n",true);
}

void
DumpTwoMatrices(file_t out,matrix_t *m1, matrix_t *m2)
{
	/*
	u32_t i,j,k,m,n,p;
	u32_t lines;
	m=m1->rows;
	n=m1->cols;
	p=m2->cols;
	*/
	umDumpMatrix(out,m1,"M1=\n",NULL,NULL,"| ","  "," |\n",true);
	umDumpMatrix(out,m2,"M2=\n",NULL,NULL,"| ","  "," |\n",true);
}

int main(int argc,char *argv[])
{
	matrix_t **mset1, **mset2, *prod;
	int i,order,n,lower,upper;
	file_t out, an;
	char *out_name;
	puts(
		"Premultiplied pairs of matrices generator ver. 2.0.\n"
		"Copyright (C) Vladimir A. Smirnov, 1997-2000.");
	if(argc<5)
	{
		puts("Usage: mgen <order> <lower limit> <upper limit> "
			"<number of pairs> [output file name] [file name for answers]");
		return -1;
	}
	order=atoi(argv[1]);
	lower=atoi(argv[2]);
	upper=atoi(argv[3]);
	n=atoi(argv[4]);
	out_name=argc<6 ? "CON" : argv[5];
	out=fileOpenWrite(out_name);
	if(!out)
	{
		printf("Unable to open '%s' for output.\n",out_name);
		return -1;
	}
	if(argc < 7)
		an=0;
	else
	{
		an=fileOpenWrite(argv[6]);
		if(!an)
		{
			printf("Unable to open '%s' for output.\n",out_name);
			fileClose(out);
			return -1;
		}
	}
	umCreateRandomMatrixSet(&mset1,n,order,order,lower,upper,false,true);
	umCreateRandomMatrixSet(&mset2,n,order,order,lower,upper,false,true);
	prod=matAlloc(order,order);
	filePrintf(out,";\t%d pairs of matrices of order %d\n;\tproduced by %s\n",
		n,order,argv[0]);
	if(an)
	{
		for(i=0;i<n;i++)
		{
			matMatMul(prod,mset1[i],mset2[i]);
			filePrintf(an,"pair %d:\n",i+1);
			umDumpMatrix(an,prod,NULL,NULL,NULL,"| ","  "," |\n",true);
			filePrintf(out,"pair %d:\n",i+1);
			DumpTwoMatrices(out,mset1[i],mset2[i]);
		}
		fileClose(an);
	}
	else
	{
		for(i=0;i<n;i++)
		{
			matMatMul(prod,mset1[i],mset2[i]);
			filePrintf(out,"pair %d:\n",i+1);
			DumpThreeMatrices(out,mset1[i],mset2[i],prod);
		}
	}
	fileClose(out);
	umDestroyRandomMatrixSet(mset1,n);
	umDestroyRandomMatrixSet(mset2,n);
	free(prod);
	return 0;
}
