/*This file Matrix.C is not to be compiled.  It is included at the end of
Matrix.h to make it easier to read the entire class project.*/

//the default constructor
template <class T>
Matrix<T>::Matrix()
{
	num_cols=0;
	num_rows=0;
	dimension=2;
	ptr_to_data = 0;
}

//will create an nxm matrix
template <class T>
Matrix<T>::Matrix(int n, int m)
{
	num_rows = n;
	num_cols = m;
	dimension=2;
	ptr_to_data = new T [n*m]; //creates matrix
}

//implements the copy constructor
template <class T>
Matrix<T>::Matrix(const Matrix<T>& a)
{
	num_rows=a.num_rows;
	num_cols=a.num_cols;
	ptr_to_data = new T [num_rows*num_cols];
	copy (a); //calls the private copy routine
}

//the array destructor
template <class T>
Matrix<T>::~Matrix()
{
	delete[] ptr_to_data;
}


//allows you to access a matrix element but not change it
template <class T>
const T& Matrix<T>::operator() (int i,int j) const
{
	if (i>=0 && j>=0 && i<num_rows && j<num_cols)
	{
    			return ptr_to_data[(i*num_cols + j)];
	}
	else
	{//throws a class in Error.h if requested element does not exist
		throw InvalidRange((i*j), __FILE__,__LINE__);

	}
}

//allows you to access the matrix elements and to set/change them
template <class T>
T& Matrix<T>::operator() (int i, int j)
{
	if (i>=0&& j>=0 && i<num_rows && j<num_cols)
	{
		   return ptr_to_data[(i*num_cols+j)];
	}
	else
	{ //throws a class in Error.h if requested element does not exist
		throw InvalidRange((i*j), __FILE__,__LINE__);
	}
}

/*The next four functions will return the number of rows and columns, the total
number of matrix elements, and the dimesion of the array.*/

template <class T>
int Matrix<T>::numRows() const
{
    return num_rows; //returns the number of rows
}

template <class T>
int Matrix<T>::numCols() const
{
    return num_cols; //returns the number of columns
}

template <class T>
int Matrix<T>::numEls()
{
    return (num_cols*num_rows); //computes and returns the number of elements }
}

template <class T>
int Matrix<T>::dim()
{
    return dimension; //returns the dimension of the array
}

/*The next two functions overload the = operator.  In the first case, we can
now set one matrix equal to another.  In the second function, we can set each
of the elements of a matrix equal to a single number.*/

template <class T>
Matrix<T>& Matrix<T>::operator = (const Matrix<T>& a)
{
    if ( ptr_to_data != a.ptr_to_data ) //makes sure they aren't already equal
    {
       setSize ( a.num_rows, a.num_cols );
       copy (a);
    }
    return *this;
}

template <class T>
Matrix<T>& Matrix<T>::operator = (T val)
{
	for (int i=0; i< (num_rows*num_cols) ; i++)
		ptr_to_data[i]=val;
	return *this;
}

/*The setSize is used to resize your current matrix.  The data that was
originally stored in the matrix will be lost.  If you don't want to lose that
data you must make a temporary copy of the original matrix before you change
its size.*/

template <class T>
void Matrix<T>::setSize (int n, int m)
{
	if ((n != num_rows)||(m != num_cols))
	{
		delete [] ptr_to_data;
		num_rows = n;
		num_cols = m;
		ptr_to_data = new T [n*m];
	}
}


//this will allow overloading of << for display purposes
template <class T>
void Matrix<T>::display (ostream& out)
{
    for (int i=0; i < num_rows; i++){
        for (int j=0; j < num_cols; j++)
            out<<setw(12)<<setprecision(5)<<ptr_to_data[j+i*num_cols];
         out<<endl;
    }
}

/*the copy function can not be accessed by the user.  It is the code which
allows one matrix to be set equal to another (with the help of the previously
defined copy constructor).*/

template <class T>
void Matrix<T>::copy (const Matrix<T>& a)
{
	for (int i=0; i< (num_cols*num_rows); i++)
		ptr_to_data[i] = a.ptr_to_data[i];

}


/*The following functions can be used to change the individual rows/colums of
the matrix.*/


//add vector v to row i of the matrix
template <class T>
Matrix<T>& Matrix<T>::addrow (int i, Vector<T>& v)
{
    if (i>=0 && i<num_rows && num_cols==v.numEls())
    {
        for (int j=0; j < num_cols; j++)
            ptr_to_data[i*num_cols+j]=ptr_to_data[i*num_cols+j]+v(j);
        return *this;
    }
    else
    { //throws a class in Error.h if requested element does not exist
		throw InvalidRange(i, __FILE__,__LINE__);
	}
}

//add vector v to column i of the matrix
template <class T>
Matrix<T>& Matrix<T>::addcol (int i, Vector<T>& v)
{
    if (i>=0 && i<num_cols && num_cols==v.numEls())
    {
        for (int j=0; j < num_rows; j++)
            ptr_to_data[j*num_cols+i]=ptr_to_data[j*num_cols+i]+v(j);
        return *this;
    }
    else
    { //throws a class in Error.h if requested element does not exist
		throw InvalidRange(i, __FILE__,__LINE__);
	}
}

//subtract vector v from the ith row of matrix
template <class T>
Matrix<T>& Matrix<T>::subrow (int i, Vector<T>& v)
{
    if (i>=0 && i<num_rows && num_cols==v.numEls())
    {
        for (int j=0; j < num_cols; j++)
            ptr_to_data[i*num_cols+j]=ptr_to_data[i*num_cols+j]-v(j);
        return *this;
    }
    else
    { //throws a class in Error.h if requested element does not exist
		throw InvalidRange(i, __FILE__,__LINE__);
	}
}

//subtract vector v from the ith column of matrix
template <class T>
Matrix<T>& Matrix<T>::subcol (int i, Vector<T>& v)
{
    if (i>=0 && i<num_cols && num_cols==v.numEls())
    {
        for (int j=0; j < num_rows; j++)
            ptr_to_data[j*num_cols+i]=ptr_to_data[j*num_cols+i]-v(j);
        return *this;
    }
    else
    { //throws a class in Error.h if requested element does not exist
		throw InvalidRange(i, __FILE__,__LINE__);
	}
}

//set the value of row i to val
template <class T>
Matrix<T>& Matrix<T>::setrow(int i, const T& val)
{
    for (int j = 0; j<num_cols; j++)
        ptr_to_data[i*num_cols+j] = val;
    return *this;
}

//set the value of column i to val
template <class T>
Matrix<T>& Matrix<T>::setcol(int i, const T& val)
{
    for (int j=0; j<num_rows; j++)
        ptr_to_data[j*num_cols+i] = val;
    return *this;
}

//mulitiply each element of row i by val
template <class T>
Matrix<T>& Matrix<T>::scalerow (int i, const T& val)
{
    if (i>=0 && i<num_rows )//make sure row i part of matrix
    {
        for (int j=0; j < num_cols; j++)
            ptr_to_data[i*num_cols+j]=ptr_to_data[i*num_cols+j]*val;
        return *this;
    }
    else
    { //throws a class in Error.h if requested element does not exist
		throw InvalidRange(i, __FILE__,__LINE__);
	}
}


//multiply each element of column i by val
template <class T>
Matrix<T>& Matrix<T>::scalecol (int i, const T& val)
{
    if (i>=0 && i<num_cols)
    {
        for (int j=0; j < num_rows; j++)
            ptr_to_data[j*num_cols+i]=ptr_to_data[j*num_cols+i]*val;
        return *this;
    }
    else
    { //throws a class in Error.h if requested element does not exist
		throw InvalidRange(i, __FILE__,__LINE__);
	}
}

//switch row i with row j
template <class T>
Matrix<T>& Matrix<T>::swaprow(int i, int j)
{
    if (i>=0 && j>=0 && i<num_rows && j <num_rows && i!=j)
    {
        T tmp;
        for (int k = 0; k<num_cols; k++){
            tmp=ptr_to_data[i*num_cols+k];
            ptr_to_data[i*num_cols+k] = ptr_to_data[j*num_cols+k];
            ptr_to_data[j*num_cols+k] = tmp;
        }
    }
    else
    { //throws a class in Error.h if requested element does not exist
		throw InvalidRange(i, __FILE__,__LINE__);
	}
}

//switch column i with column j
template <class T>
Matrix<T>& Matrix<T>::swapcol(int i, int j)
{
    if (i>=0 && j>=0 && i<num_cols && j <num_cols && i!=j)
    {
        T tmp;
        for (int k = 0; k<num_rows; k++){
            tmp=ptr_to_data[k*num_cols+i];
            ptr_to_data[k*num_cols+i] = ptr_to_data[k*num_cols+j];
            ptr_to_data[k*num_cols+j] = tmp;
        }
    }
    else
    { //throws a class in Error.h if requested element does not exist
		throw InvalidRange(i, __FILE__,__LINE__);
	}
}

/*At this point, the definitions of the arithmetic operations for matrices
begins.  While most of these functions may seem repetitive, you must explain
to the compiler how to do them.  The majority of the code is exactly as you
would expect.  More detail will be provided where things are not done in the
traditional fashion.*/

/*Addition is the first arithmetic operator that will be overloaded.  Three
types of addition must be defined matrix + matrix, number + matrix, and matrix
+ number.  The second of these must be implemented as a friend function (even
though it does the exact same thing as a matrix + number) because we can't
overload the predefined data types.  In addition += with both a matrix and a
number are defined.*/

//addition of matrices
template <class T>
inline Matrix<T> Matrix<T>::operator + (const Matrix<T>& b)
{
    Matrix<T> tmp(num_rows, num_cols);
    //both the number of rows and columns must be equal for addition
	if ( numRows() == b.numRows() && numCols() == b.numCols() )
	{
		for (int i=0; i<(num_rows*num_cols); i++)
			tmp.ptr_to_data[i]=ptr_to_data[i]+b.ptr_to_data[i];
		return tmp;
	}
	else{//throws to Error.h if addition is not allowed
		throw InvalidSizes("rows/cols", "b.rows/cols", __FILE__, __LINE__);
		}
}

//adds a number to each element of the matrix	
template <class T>
inline Matrix<T> Matrix<T>::operator + (const T val)
{
    Matrix<T> tmp(num_rows, num_cols);
	for (int i=0; i<numEls(); i++)
		tmp.ptr_to_data[i]=ptr_to_data[i]+val;
	return tmp;
}

//+= a matrix
template <class T>
inline Matrix<T>& Matrix<T>::operator += (const Matrix<T>& b)
{
    //both the number of rows and columns must be equal for addition
	if ( numRows() == b.numRows() && numCols() == b.numCols() )
	{
		for (int i=0; i<(b.numRows()*b.numCols()); i++)
			ptr_to_data[i]=ptr_to_data[i]+b.ptr_to_data[i];
		return *this;
	}
	else{//throws to Error.h if addition is not allowed
		throw InvalidSizes("rows/cols", "b.rows/cols", __FILE__, __LINE__);
		}
}

//+= a number
template <class T>
inline Matrix<T>& Matrix<T>::operator += (const T val)
{
	for (int i=0; i<numEls(); i++)
		ptr_to_data[i]=ptr_to_data[i]+val;
	return *this;
}

/*The operator overload definitions for matrix subtraction follow.  They are
the exact same functions as the ones just defined for addition.  The only
difference is that the numbers and matrix elements are being subtracted instead
of added.*/
   			
//defines the subtraction of two matrices
template <class T>
inline Matrix<T> Matrix<T>::operator - (const Matrix<T>& b)
{
    Matrix<T> tmp(num_rows, num_cols);
	if ( numRows() == b.numRows() && numCols() == b.numCols())
	{
		for (int i=0; i<(num_rows*num_cols); i++)
			tmp.ptr_to_data[i]=ptr_to_data[i]-b.ptr_to_data[i];
		return tmp;
	}
	else{
		throw InvalidSizes("rows/cols", "b.rows/cols", __FILE__, __LINE__);
	}
}

//defines a matrix - a number
template <class T>
inline Matrix<T> Matrix<T>::operator - (const T val)
{
    Matrix<T> tmp(num_rows, num_cols);
	for (int i=0; i<numEls(); i++)
		tmp.ptr_to_data[i]=ptr_to_data[i]-val;
	return tmp;
}

//-= with a matrix
template <class T>
inline Matrix<T>& Matrix<T>::operator -= (const Matrix<T>& b)
{
	if ( numRows() == b.numRows() && numCols() == b.numCols())
	{
		for (int i=0; i<(num_rows*num_cols); i++)
			ptr_to_data[i]=ptr_to_data[i]-b.ptr_to_data[i];
		return *this;
	}
	else{
		throw InvalidSizes("rows/cols", "b.rows/cols", __FILE__, __LINE__);
	}
}

//-= with a number
template <class T>
inline Matrix<T>& Matrix<T>::operator -= (const T val)
{
	for (int i=0; i<numEls(); i++)
		ptr_to_data[i]=ptr_to_data[i]-val;
	return *this;
}

/*The definitions for multiplication are defined below.  The same types of
functions as in the case of addition and subtraction are used.  The fact that
that the data is stored as a line instead of an array leads to some
diffuculties.  The usual way to do the multipication is with three nested for
loops.  This type of solution can not be used here so this routine may be
slightly different than what you might have expected.*/

//multiply two matrices together
template <class T>
inline Matrix<T> Matrix<T>::operator * (const Matrix<T>& b)
{
    if (numCols()==b.numRows())//sees if multipication is allowed
    {
	Matrix<T> tmp(numRows(), b.numCols());//where the result will be stored
	tmp=0;
	int k = 0;
	//the two while loops work in a similar fashion to the original two outer
	//for loops.
	while (k<numRows())
	{
	   int j = 0;
	   while ( j < b.numCols())
	   {
	      T sum=0.0;
	      //thise is the same idea as the original versions inner for loop
	      for (int i = 0; i < numCols(); i++)
	         sum +=ptr_to_data[i+k*numCols()]*
			b.ptr_to_data[j+(i*b.numCols())]; 	
	      tmp.ptr_to_data[j + (k*b.numCols())]=sum;//each element of mult
	      j++;
	   }
 	   k++;
	}
	for (int i=0; i<(tmp.num_rows*tmp.num_cols);i++)
	    if (fabs(tmp.ptr_to_data[i]) < 1e-12)
	        tmp.ptr_to_data[i] = 0;  //set to zero if restult to small
	return tmp;
     }
     else{//thrown to Error.h if multiplication is not allowed
        throw InvalidSizes("numRows()","b.numCols()", __FILE__, __LINE__);
     }
}

//muliples a number to each matrix element
template <class T>
inline Matrix<T> Matrix<T>::operator * (const T val)
{
    Matrix<T> tmp(num_rows, num_cols);
	for (int i=0; i<numEls(); i++)
		tmp.ptr_to_data[i]=ptr_to_data[i] * val;
	return tmp;
}

//*= with another matrix
template <class T>
inline Matrix<T>& Matrix<T>::operator *= (const Matrix<T>& b)
{
	if (numCols()==b.numRows())//sees if multipication is allowed
    {
	Matrix<T> tmp(numRows(), b.numCols());//where the result will be stored
	tmp=0;
	int k = 0;
	//the two while loops work in a similar fashion to the original two outer
	//for loops.
	while (k<numRows())
	{
	   int j = 0;
	   while ( j < b.numCols())
	   {
	      T sum=0.0;
	      //thise is the same idea as the original versions inner for loop
	      for (int i = 0; i < numCols(); i++)
	         sum +=ptr_to_data[i+k*numCols()]*
			b.ptr_to_data[j+(i*b.numCols())]; 	
	      tmp.ptr_to_data[j + (k*b.numCols())]=sum;//each element of mult
	      j++;
	   }
 	   k++;
	}
	for (int i=0; i<(tmp.num_rows*tmp.num_cols);i++)
	    if (fabs(tmp.ptr_to_data[i]) < 1e-12)
	        tmp.ptr_to_data[i] = 0;  //set to zero if restult to small
	*this = tmp;
	return *this;
    }
    else{//thrown to Error.h if multiplication is not allowed
       throw InvalidSizes("numRows()","b.numCols()", __FILE__, __LINE__);
    }
}

//*= with a number
template <class T>
inline Matrix<T>& Matrix<T>::operator *= (const T val)
{
	for (int i=0; i<numEls(); i++)
		ptr_to_data[i]=ptr_to_data[i] * val;
	return *this;
}

/*Division operators are the final operators that will be overloaded for
matrices.  These functions are of the same structure as those that have been
previously defined for addition. subtraction, and multiplication*/

//divides two matrices (error check in multiplication and inverse functions)
template<class T>
inline Matrix<T> Matrix<T>::operator / (const Matrix<T>& b)
{
    Matrix<T> tmp = inverse(b);
    Matrix<T> tmp2 = *this;
    tmp *= tmp2;
    for (int i=0; i<(num_rows*num_cols); i++)
        if ( fabs(tmp.ptr_to_data[i]) < 1e-12)
            tmp.ptr_to_data[i] = 0.0;//sets value to zero if really small
    return tmp;
}

//divides each matrix element by a number
template<class T>
inline Matrix<T> Matrix<T>::operator / (const T val)
{
    Matrix<T> tmp(num_rows, num_cols);
    for (int i = 0; i<numEls(); i++)
        tmp.ptr_to_data[i] = ptr_to_data[i]/val;
    return tmp;
}

// /=with two matrices
template <class T>
inline Matrix<T>& Matrix<T>::operator /= (const Matrix<T>& b)
{
 Matrix<T> tmp = inverse(b);
    Matrix<T> tmp2 = *this;
    tmp *= tmp2;
    for (int i=0; i<(num_rows*num_cols); i++)
        if ( fabs(tmp.ptr_to_data[i]) < 1e-12)
            tmp.ptr_to_data[i] = 0.0;//sets value to zero if really small
    *this = tmp;
    return *this;
}

//divides each matrix element by a number
template <class T>
inline Matrix<T>& Matrix<T>::operator /= (const T val)
{
    Matrix<T> tmp(num_rows, num_cols);
    for (int i = 0; i<numEls(); i++)
        tmp.ptr_to_data[i] = ptr_to_data[i]/val;
    *this = tmp;
    return *this;
}

/*The remainig functions are matrix inverse, transpose, gauss, and determinant.
The gauss function was defined as a friend function to simplify the
implementation of the code.  It is used to find an uppertriangular version of
the input matrix for the determinant function.*/

//finds the transpose of a matrix (this is a virtual fuction)
template <class T>
Matrix<T>& Matrix<T>::transpose()
{	
	Matrix<T> c(num_cols, num_rows);
	for (int i=0; i<num_cols; i++){
		for (int j=0; j<num_rows; j++)
			c(i,j)= ptr_to_data[i+j*num_cols];
	}
	*this=c;
	return *this;
}

//finds the determinant of a square matrix
template <class T>
T Matrix<T>::determinant ()
{
	T det = 1.0;
	Matrix<T> tmp=gauss(*this);
	for (int i=0; i<numRows(); i++)
		det *= tmp(i,i);
	return det;
}
