/*
	BigMatrix.cpp
	=============
*/

#include <stdlib.h>
#include "BigMatrix.h"



// ===========================================================================
// BigVector member functions
// ===========================================================================

inline void BigVector::setall (BigFloat x)
{
	BigFloat* p   = data;
	BigFloat* end = p + length;
	while (p < end)                           // set every array element to x
		*(p++) = x;
}


inline void BigVector::create (BigInt n)
{
	n = n>0 ? n : 0;
	data = n ? new BigFloat[n] : 0;           // allocate vector array
	if(n && !data)
		throw BigMatrixOutOfMemory();
	length = n;
	if(!(nref = new unsigned int))            // allocate reference counter
		throw BigMatrixOutOfMemory();
	*nref = 1;                                // initialize reference count
}


inline void BigVector::destroy()
{
	if(--(*nref)) return;          // don't delete if more than one reference
	delete[] data;
	delete   nref;
}


inline void BigVector::clone()
{
	if(*nref<=1) return;           // don't clone if only one reference
	(*nref)--;
	BigFloat* p2  = data;
	create(length);                // allocate memory for cloned vector
	BigFloat* p1  = data;
	BigFloat* end = p1 + length;
	while (p1 < end)               // copy every vector element from original
		*(p1++) = *(p2++);
}


const BigVector& BigVector::operator=(const BigVector & v)
{
	if(data != v.data)             // don't copy if vectors are identical
	{
		destroy();                 // delete old vector data
		data = v.data;             // copy vector header
		length = v.length;
		nref = v.nref;
		(*nref)++;                 // increase reference count
	}
	return *this;
}


const BigVector& BigVector::operator=(BigFloat x)
{
	setall(x);
	return *this;
}


BigFloat& BigVector::operator()(BigInt i)
{
	--i;
	if( i<0 || i>=length)
		throw BigMatrixOutOfBounds();
	clone();                        // clone since vector might be changed
	return data[i];
}


const BigFloat& BigVector::operator()(BigInt i) const
{
	--i;
	if( i<0 || i>=length)
		throw BigMatrixOutOfBounds();
	return data[i];
}


const BigVector BigVector::operator+(const BigVector & v) const
{
	BigVector v3 = *this;
	v3 += v;
	return v3;
}


const BigVector BigVector::operator-(const BigVector & v) const
{
	BigVector v3 = *this;
	v3 -= v;
	return v3;
}


BigVector& BigVector::operator+=(const BigVector & v)
{
	if(size() != v.size())
		throw BigMatrixIncompatible();
	clone();
	BigFloat* p1  = data;
	BigFloat* p2  = v.data;
	BigFloat* end = p1 + length;
	while (p1 < end)
		*(p1++) += *(p2++);
	return *this;
}


BigVector& BigVector::operator-=(const BigVector & v)
{
	if(size() != v.size())
		throw BigMatrixIncompatible();
	clone();
	BigFloat* p1  = data;
	BigFloat* p2  = v.data;
	BigFloat* end = p1 + length;
	while (p1 < end)
		*(p1++) -= *(p2++);
	return *this;
}


const BigVector BigVector::operator- () const
{
	BigVector v2 = *this;
	v2.clone();
	BigFloat* p1  = v2.data;
	BigFloat* end = p1 + v2.length;
	while (p1 < end)
	{
		*p1 = -*p1;
		++p1;
	}
	return v2;
}


const BigVector BigVector::operator+(BigFloat x) const
{
	BigVector v = *this;
	v += x;
	return v;
}


BigVector& BigVector::operator+=(BigFloat x)
{
	clone();
	BigFloat* p1  = data;
	BigFloat* end = p1 + length;
	while (p1 < end)
		*(p1++) += x;
	return *this;
}


BigFloat BigVector::operator*(const BigVector & v) const
{
	if(size() != v.size())
		throw BigMatrixIncompatible();
	BigFloat* p1  = data;
	BigFloat* p2  = v.data;
	BigFloat* end = p1 + length;
	BigFloat sum = 0;
	while (p1 < end)
		sum += (*(p1++)) * (*(p2++));
	return sum;
}


const BigVector BigVector::operator*(BigFloat x) const
{
	BigVector v = *this;
	v *= x;
	return v;
}


BigVector& BigVector::operator*=(BigFloat x)
{
	clone();
	BigFloat* p1  = data;
	BigFloat* end = p1 + length;
	while (p1 < end)
		*(p1++) *= x;
	return *this;
}


int BigVector::operator==(const BigVector & v) const
{
	if(size() != v.size())
		return false;
	if(data == v.data)
		return true;
	BigFloat* p1  = data;
	BigFloat* p2  = v.data;
	BigFloat* end = p1 + length;
	while (p1 < end)
		if(*(p1++) != *(p2++))
			return false;
	return true;
}


void BigVector::resize(BigInt n)
{
	destroy();
	create(n);
	setall(0.0);
}


int BigVectorCompareSmaller(const void* x1, const void* x2)
{                                                  // comparison function for qsort
	if(*(BigFloat*) x1 < *(BigFloat*) x2) return -1;
	if(*(BigFloat*) x1 > *(BigFloat*) x2) return 1;
	return 0;
}

void BigVector::sort_ascending()
{
	clone();
	qsort((void*) data, length, sizeof(BigFloat), &BigVectorCompareSmaller);
}


int BigVectorCompareBigger(const void* x1, const void* x2)
{                                                  // comparison function for qsort
	if(*(BigFloat*) x1 < *(BigFloat*) x2) return 1;
	if(*(BigFloat*) x1 > *(BigFloat*) x2) return -1;
	return 0;
}

void BigVector::sort_descending()
{
	clone();
	qsort((void*) data, length, sizeof(BigFloat), &BigVectorCompareBigger);
}



// ===========================================================================
// BigMatrix member functions
// ===========================================================================


BigInt BigMatrix::scan_ptr::advance()
{                                    // search for next non-zero matrix element
	if(current)
		if(current = current->next)  // if following element in same column
			return col;
	while(col < matrix->length)      // look for element in next column
		if(current = matrix->col[col++].first)
			return col;
	col = 0;
	current = 0;
	return 0;
}


BigInt BigMatrix::scan_ptr::gotocol(BigInt icol)
{                                                    // go to column 'icol'
	if( icol<=0 || icol>matrix->length)
		throw BigMatrixOutOfBounds();
	col = icol;
	current = matrix->col[col-1].first;
	return col;
}


BigInt BigMatrix::create (BigInt n)
{
	n = n>0 ? n : 0;
	col = n ? new column[n] : 0;         // allocate array of column pointers
	if(n && !col)
		throw BigMatrixOutOfMemory();
	length = n;
	if(!(nref = new unsigned int))       // allocate reference counter
		throw BigMatrixOutOfMemory();
	(*nref) = 1;                         // initialize reference count
	return n;
}


void BigMatrix::destroy()
{
	if(--(*nref)) return;            // don't delete if more than one reference
	column* cp0 = col;
	column* cp	= cp0 + length;
	while(cp > cp0)                  // loop trough all columns
	{
		element* ep = (--cp)->first;
		while(ep)                    // follow linked list and delete elements
		{
			element* epold = ep;
			ep = ep->next;
			delete epold;
		}
	}
	delete[] col;
	delete	 nref;
}


void BigMatrix::clone()
{
	if(*nref<=1) return;                // don't clone if only one reference
	(*nref)--;
	column* cp1 = col;
	column* end = cp1 + length;
	create(length);                     // allocate memory for cloned vector
	column* cp2 = col;
	while(cp1 < end)                    // loop trough all columns
	{
		element*  ep1  =  cp1->first;
		element** epp2 = &cp2->first;
		while(ep1)                      // follow list and copy each element
		{
			if(!(*epp2 = new element(ep1->row, ep1->value)))
				throw BigMatrixOutOfMemory();
			if(!(ep1 = ep1->next)) break;
			epp2 = &(*epp2)->next;
		}
		cp2->last = *epp2;
		cp2->nfirst = cp1->nfirst;
		cp2->nlast  = cp1->nlast;
		cp1++;
		cp2++;
	}
}


BigMatrix::element_ptr BigMatrix::find(column* cp, BigInt i)
{
	element_ptr ep(cp,i);
	if(cp->first)                        // if linked list is not empty
	{
		if(i > cp->nlast)                // if element after last in list
			ep.previous = cp->last;
		else if(i >= cp->nfirst)         // if element not before first in list
		{
			element* prev = 0;
			for(element* p = cp->first; p->row < i; p = p->next)
				prev = p;
			if(p->row == i)
				ep.current = p;
			ep.previous = prev;
		}
	}
	return ep;
}


void BigMatrix::set(element_ptr& ep, BigFloat x)
{
	if(x == 0.0)                         // if matrix element is zero delete it
	{
		if(!ep.current) return;          // if element not allocated skip
		if(!ep.previous)                 // if element is first in list
			ep.col->nfirst = (ep.col->first=ep.current->next) ? ep.col->first->row : 0;
		else
			ep.previous->next = ep.current->next;
		if(!ep.current->next)            // if element is last in list
			ep.col->nlast = (ep.col->last=ep.previous) ? ep.previous->row : 0;
		delete ep.current;
		ep.current = 0;
	}
	else                                 // if element is non-zero then set it
	{
		if(!ep.current)                  // if element not allocated
		{
			if(!(ep.current = new element(ep.row, x)))
				throw BigMatrixOutOfMemory();
			if(!ep.previous)             // if element is first in list
			{
				ep.current->next = ep.col->first;
				ep.col->first = ep.current;
				ep.col->nfirst = ep.row;
			}
			else
			{
				ep.current->next  = ep.previous->next;
				ep.previous->next = ep.current;
			}
			if(!ep.current->next)        // if element is last in list
			{
				ep.col->last  = ep.current;
				ep.col->nlast = ep.row;
			}
		}
		else                             // if element exists just change it
			ep.current->value = x;
	}
}


BigMatrix::BigMatrix(BigInt n, BigFloat x)
{
	n = create(n);
	for(BigInt i=1; i<=n; ++i)       // set diagonal matrix elements
		(*this)(i,i) = x;
}


BigMatrix::BigMatrix(const BigVector & v)
{
	BigInt n = v.size();
	n = create(n);
	for(BigInt i=1; i<=n; ++i)       // set diagonal matrix elements
		(*this)(i,i) = v(i);
}


const BigMatrix& BigMatrix::operator= (const BigMatrix & m)
{
	if(col != m.col)                 // don't copy if matrices are identical
	{
		destroy();                   // delete old matrix
		col = m.col;                 // copy header
		length = m.length;
		nref = m.nref;
		(*nref)++;                   // increase reference count
	}
	return *this;
}


const BigMatrix& BigMatrix::operator= (const BigVector & v)
{
	destroy();
	BigInt n = v.size();
	n = create(n);
	for(BigInt i=1; i<=n; ++i)
		(*this)(i,i) = v(i);
	return *this;
}


const BigMatrix& BigMatrix::operator= (BigFloat x)
{
	BigInt n = size();
	destroy();
	create(n);
	for(BigInt i=1; i<=n; ++i)
		(*this)(i,i) = x;
	return *this;
}


BigMatrix::element_ptr BigMatrix::operator()(BigInt i,BigInt j)
{
	if( i<=0 || i>length || j<=0 || j>length)
		throw BigMatrixOutOfBounds();
	if(*nref>1)
		clone();                       // clone since matrix might be changed
	return find(col+j-1, i);
}


const BigFloat BigMatrix::operator()(BigInt i,BigInt j) const
{
	if( i<=0 || i>length || j<=0 || j>length)
		throw BigMatrixOutOfBounds();
	return find(col+j-1, i);
}


const BigMatrix BigMatrix::operator+ (const BigMatrix & m) const
{
	BigMatrix m2 = *this;
	m2 += m;
	return m2;
}


const BigMatrix BigMatrix::operator- (const BigMatrix & m) const
{
	BigMatrix m2 = *this;
	m2 -= m;
	return m2;
}


BigMatrix& BigMatrix::operator+=(const BigMatrix & m)
{
	if(size() != m.size())
		throw BigMatrixIncompatible();
	clone();
	scan_ptr sp(m);     // 'sp' is pointing at first non-zero matrix elements
	while(sp.current)   // scan through all non-zero matrix elements of m
	{
		(*this)(sp.current->row, sp.col) += sp.current->value;
		sp.advance();
	}
	return *this;
}


BigMatrix& BigMatrix::operator-=(const BigMatrix & m)
{
	if(size() != m.size())
		throw BigMatrixIncompatible();
	clone();
	scan_ptr sp(m);
	while(sp.current)
	{
		(*this)(sp.current->row, sp.col) -= sp.current->value;
		sp.advance();
	}
	return *this;
}


const BigMatrix BigMatrix::operator- () const
{
	BigMatrix m2 = *this;
	m2.clone();
	scan_ptr sp(m2);
	while(sp.current)
	{
		sp.current->value = -sp.current->value;
		sp.advance();
	}
	return m2;
}


const BigMatrix BigMatrix::operator+ (const BigVector & v) const
{
	BigMatrix m2 = *this;
	m2 += v;
	return m2;
}


const BigMatrix BigMatrix::operator- (const BigVector & v) const
{
	BigMatrix m2 = *this;
	m2 -= v;
	return m2;
}


BigMatrix& BigMatrix::operator+=(const BigVector & v)
{
	BigInt n = v.size();
	if(size() != n)
		throw BigMatrixIncompatible();
	clone();
	for(BigInt i=1; i<=n; ++i)
		(*this)(i,i) += v(i);
	return *this;
}


BigMatrix& BigMatrix::operator-=(const BigVector & v)
{
	BigInt n = v.size();
	if(size() != n)
		throw BigMatrixIncompatible();
	clone();
	for(BigInt i=1; i<=n; ++i)
		(*this)(i,i) -= v(i);
	return *this;
}


const BigMatrix BigMatrix::operator+ (BigFloat x) const
{
	BigMatrix m2 = *this;
	m2 += x;
	return m2;
}


BigMatrix& BigMatrix::operator+=(BigFloat x)
{
	BigInt n = size();
	clone();
	for(BigInt i=1; i<=n; ++i)
		(*this)(i,i) += x;
	return *this;
}


BigMatrix BigMatrix::operator* (const BigMatrix & m) const
{                                                     // matrix multiplication
	if(size() != m.size())
		throw BigMatrixIncompatible();
	BigMatrix m2(size());
	scan_ptr sp(m);      // 'sp' is pointing at first non-zero matrix elements
	while(sp.current)    // scan through all non-zero matrix elements of m
	{
		BigInt mrow = sp.current->row;
		element* ep = col[mrow-1].first;
		while(ep)        // scan through appropriate column of matrix '*this'
		{
			m2(ep->row, sp.col) += sp.current->value * ep->value;
			ep = ep->next;
		}
		sp.advance();
	}
	return m2;
}


BigVector BigMatrix::operator* (const BigVector & v) const
{
	if(size() != v.size())
		throw BigMatrixIncompatible();
	BigVector v2(v.size());
	scan_ptr sp(*this);
	while(sp.current)   // scan through all non-zero matrix elements of '*this'
	{
		v2(sp.current->row) += v(sp.col) * sp.current->value;
		sp.advance();
	}
	return v2;
}


BigMatrix BigMatrix::operator* (BigFloat x) const
{
	BigMatrix m2 = *this;
	m2 *= x;
	return m2;
}


BigMatrix& BigMatrix::operator*=(const BigMatrix & m)
{
	if(size() != m.size())
		throw BigMatrixIncompatible();
	*this = (*this) * m;
	return *this;
}


BigMatrix& BigMatrix::operator*=(BigFloat x)
{
	clone();
	scan_ptr sp(*this);
	while(sp.current)
	{
		sp.current->value *= x;
		sp.advance();
	}
	return *this;
}


int BigMatrix::operator==(const BigMatrix & m) const
{
	if(size() != m.size()) return false;
	if(col == m.col) return true;
	scan_ptr sp1(*this);
	scan_ptr sp2(m);
	while(sp1.current && sp2.current)
	{
		if(sp1.current->value == 0.0) { sp1.advance(); continue; }
		if(sp2.current->value == 0.0) { sp2.advance(); continue; }
		if(sp1.current->value != sp2.current->value) return false;
		if(sp1.col != sp2.col) return false;
		if(sp1.current->row != sp2.current->row)     return false;
		sp1.advance();
		sp2.advance();
	}
	while(sp1.current)
	{
		if(sp1.current->value != 0.0) break;
		sp1.advance();
	}
	while(sp2.current)
	{
		if(sp2.current->value != 0.0) break;
		sp2.advance();
	}
	if(sp1.current) return false;
	if(sp2.current) return false;
	return true;
}


void BigMatrix::resize(BigInt n)
{
	destroy();
	create(n);
}


void BigMatrix::delete_column(BigInt i)
{
	clone();
	element* ep = col[i-1].first;
	while(ep)                         // follow linked list and delete elements
	{
		element* epold = ep;
		ep = ep->next;
		delete epold;
	}
	col[i-1].first  = 0;
	col[i-1].last   = 0;
	col[i-1].nfirst = 0;
	col[i-1].nlast  = 0;
}


void BigMatrix::delete_lower_triangle()
{
	clone();
	scan_ptr sp(*this);
	while(sp.valid())
	{
		BigInt row = sp.row();
		BigInt col = sp.column();
		sp.advance();
		if(row > col) (*this)(row,col) = 0.0;   // delete elements in lower triangle
	}
}


void BigMatrix::write_matrix(ostream & out)
{
	scan_ptr sp(*this);
	while(sp.current)
	{
		out << sp.row() << " " << sp.column() << " " << sp.get() << endl;
		sp.advance();
	}
}


long int BigMatrix::read_matrix (istream & in, long int max)
{
	BigInt n = size();
	for(long int i=0; i!=max && !in.eof(); i++)
	{
		BigInt row = 0;
		BigInt col = 0;
		BigFloat x = 0.0;
		in >> row >> col >> x;
		if( row < 1 || col < 1 ) throw BigMatrixReadError();
		if( row > n || col > n ) throw BigMatrixReadError();
		(*this)(row,col) = x;
	}
	return i;
}



// ===========================================================================
// non-member functions
// ===========================================================================

BigMatrix transpose(BigMatrix & m)
{
	BigMatrix m2(m.size());
	BigMatrix::scan_ptr sp(m);
	while(sp.valid())
	{
		m2(sp.column(), sp.row()) = sp.get();
		sp.advance();
	}
	return m2;
}



// ==================
// SymmetricBigMatrix
// ==================


void SymmetricBigMatrix::clone()
{
	BigMatrix::clone();
	delete_lower_triangle();
	(*this) += transpose(*this);
	for(BigInt i=1; i<=size(); i++)
		(*this)(i) /= 2;
}


const SymmetricBigMatrix& SymmetricBigMatrix::operator= (const SymmetricBigMatrix & m)
{
	if(col != m.col)                 // don't copy if matrices are identical
	{
		destroy();                   // delete old matrix
		col = m.col;                 // copy header
		length = m.length;
		nref = m.nref;
		(*nref)++;                   // increase reference count
	}
	return *this;
}


BigMatrix::element_ptr SymmetricBigMatrix::operator()(BigInt i,BigInt j)
{
	if( i<=0 || i>length || j<=0 || j>length)
		throw BigMatrixOutOfBounds();
	if(*nref>1)
		clone();
	return i<j ? find(col+j-1, i) : find(col+i-1, j);
}


const BigFloat SymmetricBigMatrix::operator()(BigInt i,BigInt j) const
{
	if( i<=0 || i>length || j<=0 || j>length)
		throw BigMatrixOutOfBounds();
	return i<j ? find(col+j-1, i) : find(col+i-1, j);
}

