//	StepStream.cxx

#include "StepStrm.h"
#include <iostream.h>
#include <string.h>

#ifndef TAB
#define TAB '\t'
#endif

StepStream::StepStream( void )
: T(0), Delimiter(TAB), itsOutStream(NULL), OutputOnStep(0),
  itsPrecision(0), itsHighColNum(-1)
{
	for (int i=0; i<kSSMaxCols; i++) {
		itsColHeader[i][0] = 0;
		itsColVar[i] = NULL;
	}
}

StepStream::StepStream( ostream& pStream )
: T(0), Delimiter(TAB), itsOutStream(&pStream), OutputOnStep(0),
  itsPrecision(0), itsHighColNum(-1)
{
	for (int i=0; i<kSSMaxCols; i++) {
		itsColHeader[i][0] = 0;
		itsColVar[i] = NULL;
	}
}

int StepStream::SetColumn( const int pCol, real *pVar, const char* pHeader)
{
	if (pCol > kSSMaxCols) {
		cerr << "\nerror in StepStream::SetColumn -- max columns exceeded\n";
		return 0;
	}
	itsColVar[pCol] = pVar;
	if (!pVar || !pHeader) {
		// clearing this column; clear the header, check itsHighColNum
		itsColHeader[pCol][0] = 0;
		while (!itsColVar[itsHighColNum] && itsHighColNum >= -1)
			itsHighColNum--;
	}
	else {
		// adding a var: set the header, check itsHighColNum
		strncpy( itsColHeader[pCol], pHeader, kSSHeaderLen );
		itsColHeader[pCol][kSSHeaderLen-1] = 0;
		if (pCol > itsHighColNum) itsHighColNum = pCol;
	}
	
	return 1;
}

const char *StepStream::GetHeader( const int pCol ) const
{
	if (pCol > kSSMaxCols) {
		cerr << "\nerror in StepStream::GetHeader -- max columns exceeded\n";
		return " ";
	}
	return itsColHeader[pCol];
}

real StepStream::GetValue( const int pCol ) const
{
	if (pCol > kSSMaxCols) {
		cerr << "\nerror in StepStream::GetValue -- max columns exceeded\n";
		return 0;
	}
	return *itsColVar[pCol];
}

void StepStream::Output( ostream* pStream ) const
{
	ostream *out = (pStream ? pStream : itsOutStream);
	if (!out) return;
	int qty = 0;
	for (int i=0; i<=itsHighColNum; i++) {
		if (itsColVar[i]) {
			if (qty) *out << Delimiter;
			if (itsPrecision) {
				out->precision(itsPrecision);
				out->setf(ios::showpoint);
			}
			*out << *itsColVar[i];
			qty++;
		}
	}
	*out << '\n';
}

void StepStream::OutputHeader( ostream* pStream ) const
{
	ostream *out = (pStream ? pStream : itsOutStream);
	if (!out) return;

	for (int i=0; i<=itsHighColNum; i++) {
		if (i) *out << Delimiter;
		if (itsColVar[i]) *out << itsColHeader[i];
	}
	*out << '\n';
}
