/*

cls_2: Curl Like Syntax
Yauheni A. Akhotnikau (C) 2001-2003
eao197@yahoo.com
-------------------------------------------------

Permission is granted to anyone to use this software for any purpose on any
computer system, and to redistribute it freely, subject to the following
restrictions:

1. This software is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

2. The origin of this software must not be misrepresented, either by
   explicit claim or by omission.

3. Altered versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

-------------------------------------------------

*/
/*!
	\file
	\brief Класс потока ошибок, который отображает имя файла
		и текущий номер строки.
	
*/

#include <assert.h>
#include <string.h>
#include <stdio.h>

#include <cls_2/h/es_file_line_num.hpp>

namespace cls_2
{

//
// es_file_line_num_t
//

es_file_line_num_t::es_file_line_num_t(
	error_stream_t & real_err_stream,
	const input_stream_file_t & file )
:
	m_real_err_stream( &real_err_stream, false ),
	m_in( file ),
	m_is_new_line( true )
{
	set_file_name( file.query_file_name() );
}

es_file_line_num_t::es_file_line_num_t(
	const auto_ptr_3::obj_destruction_t< error_stream_t > & to,
	const char * file_name,
	const input_stream_t & in )
:
	m_real_err_stream( to ),
	m_in( in ),
	m_is_new_line( true )
{
	set_file_name( file_name );
}

es_file_line_num_t::~es_file_line_num_t()
{
}

error_stream_t &
es_file_line_num_t::out( const char * str )
{
	if( m_is_new_line )
	{
		// File name and line number must be printed
		char sz[ 24 ];
		sprintf( sz, ":%u: ", m_in.query_line() );
		m_real_err_stream->out( m_file_name.query() ).out( sz );

		m_is_new_line = false;
	}

	m_real_err_stream->out( str );
	if( str )
	{
		size_t l = strlen( str );
		if( l && '\n' == str[ l - 1 ] )
			m_is_new_line = true;
	}

	return *this;
}

void
es_file_line_num_t::set_file_name(
	const char * file_name )
{
	assert( file_name );
	size_t l = strlen( file_name );
	m_file_name.destroy();
	m_file_name.set( new char[ l + 1 ], l + 1 );
	strcpy( m_file_name.query(), file_name );
}

} /* namespace cls_2 */
