/**********************************************************************************
 * iniOpen
 *
 *
 **************************************************
 * This code was created by Peter Harvey @ CodeByDesign.
 * Released under LGPL 28.JAN.99
 *
 * Contributions from...
 * -----------------------------------------------
 * PAH = Peter Harvey		- pharvey@codebydesign.com
 * -----------------------------------------------
 *
 * PAH	06.MAR.99	Can now create file-less INI. Pass NULL for
 *					pszFileName. Then copy a file name into hIni->szFileName
 *					before calling iniCommit.
 **************************************************/

#include "ini.h"

int iniOpen( HINI *hIni, char *pszFileName, char cComment, char cLeftBracket, char cRightBracket, char cEqual, int bCreate )
{
   FILE    *hFile;
	char    szLine[INI_MAX_LINE+1];
	char	szObjectName[INI_MAX_OBJECT_NAME+1];
	char	szPropertyName[INI_MAX_PROPERTY_NAME+1];
	char	szPropertyValue[INI_MAX_PROPERTY_VALUE+1];

    /* INIT STATEMENT */
    *hIni = malloc( sizeof(INI) );
	if ( pszFileName )
		strncpy( (*hIni)->szFileName, pszFileName, FILENAME_MAX );
	else
		strncpy( (*hIni)->szFileName, "", FILENAME_MAX );
    (*hIni)->cComment         	= cComment;
    (*hIni)->cLeftBracket     	= cLeftBracket;
    (*hIni)->cRightBracket    	= cRightBracket;
    (*hIni)->cEqual           	= cEqual;
    (*hIni)->bChanged			= FALSE;
    (*hIni)->hCurObject			= NULL;
    (*hIni)->hFirstObject		= NULL;
    (*hIni)->hLastObject		= NULL;
    (*hIni)->nObjects			= 0;
	(*hIni)->bReadOnly			= 0;

    /* OPEN FILE */
	if ( pszFileName )
	{
		hFile = fopen( pszFileName, "r" );
		if ( !hFile )
		{
			if ( bCreate == TRUE )
			{
				hFile = fopen( pszFileName, "w" );
			}
		}

		if ( !hFile )
		{
			free( *hIni );
			*hIni = NULL;
			return INI_ERROR;
		}

		if ( _iniScanUntilObject( *hIni, hFile, szLine ) == INI_SUCCESS )
		{
			do
			{
				if ( szLine[0] == cLeftBracket )
				{
					_iniObjectRead( (*hIni), szLine, szObjectName );
					iniObjectInsert( (*hIni), szObjectName );
				}
				else if ( (szLine[0] != cComment) && isalnum(szLine[0]) )
				{
					_iniPropertyRead( (*hIni), szLine, szPropertyName, szPropertyValue );
					iniPropertyInsert( (*hIni), szPropertyName, szPropertyValue );
				}

			} while( fgets( szLine, INI_MAX_LINE, hFile ) != NULL );
		}

		/* CLEANUP */
		if ( hFile != NULL )
			fclose( hFile );

		iniObjectFirst( *hIni );

	} /* if file given */

    return INI_SUCCESS;
}


