// ------------------------------------------------------------------------
/*
	author: Jaap Suter
   
	Copyright (C) Electronic Arts Canada Inc. 2002.  All rights reserved.	
*/
// ------------------------------------------------------------------------

/*! \file */

#include "reveal/serialize.h"

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

#if defined __GNUC__
#define _snprintf snprintf
#endif

namespace Reveal {

// ------------------------------------------------------------------------------
void Serialize::Save( File f, const char* data )
{
	// Create a huge big-ass buffer;
	// \todo Fix this;
	const size_t bufferSize = 65536; 
	char buffer[ bufferSize ]; memset( buffer, 0, bufferSize );
	char line[   bufferSize	]; memset( line, 0, bufferSize );

	// Load the buffer;
	Load( f, buffer, bufferSize );

	// Merge the data;
	for (;;)
	{
		const char* pathAndNameEnd = data;
		for ( size_t i = 0; i < 4; ++i ) 
		{ 
			pathAndNameEnd = strchr( pathAndNameEnd, '\"' );
			if ( pathAndNameEnd == NULL ) break;
			++pathAndNameEnd;
		}
		strncpy( line, data, pathAndNameEnd - data );
		line[ pathAndNameEnd - data ] = '\0';
		
		// See if there is already a value with that name and path, in there;
		char* lineInDst = buffer;
		lineInDst = strstr( buffer, line );
		if ( lineInDst )
		{
			// There is, so we remove it. We find the end of the line;
			char* lineInDstEnd = lineInDst + strlen( line ) + 1;
			for ( size_t i = 0; i < 2; ++i ) 
			{ 
				lineInDstEnd = strchr( lineInDstEnd, '\"' );
				++lineInDstEnd;
			}
			
			// And move the end over it;
			memmove( lineInDst, lineInDstEnd + 1, strlen( lineInDstEnd ) );
		}

		// Put it in;
		const char* dataEnd = pathAndNameEnd;
		dataEnd = strchr( dataEnd, '\n' );
		if ( dataEnd == NULL ) break;
		++dataEnd;
		strncpy( line, data, dataEnd - data );
		line[ dataEnd - data ] = '\0';
		size_t bufferEnd = strlen(buffer);
		_snprintf( &buffer[bufferEnd], sizeof(buffer) - bufferEnd, "%s", line );
		buffer[ sizeof(buffer) - 1 ] = '\0';
		data = dataEnd;
		if ( *data   == '\0' ) break;
	}

	// Save the buffer;
	DoSave( f, buffer );
}

// ------------------------------------------------------------------------------
void Serialize::Load( File f, char* buffer, size_t size )
{
	DoLoad( f, buffer, size );
}

} // Namespace Reveal;

#if defined __GNUC__
#undef _snprintf 
#endif

