/*
    This file is part of SUPPL - the supplemental library for DOS
    Copyright (C) 1996-2000 Steffen Kaiser

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 of the License, or (at your option) any later version.

    This library 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.  See the GNU
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* $RCSfile: CFGI_CFI.C $
   $Locker: ska $	$Name:  $	$State: Exp $

	int cfgi_createFile(char *fnam)

	Create specific INI file

	Return:
		0 on success

ob: cfgi_createFile
ty: LH
su: inifile/1
sh: Open an INI file for writing
lo: Opens the specified INI file for writing.\par
	Instead of immediately creating the file the supplied filename is
	duplicated into the heap and a temporary file is opened. When the
	INI file has been written successfully, the temporary file is renamed to
	the cached filename.\par
	This way, the original INI file remains present and accessable until the
	new contents has been constructed wholely.
re: cfgi_ini cfgi_fnam cfgiCloseCreateINI
fi: cfgi_cfi.c
in:

*/

#include "initsupl.loc"

#ifndef _MICROC_
#include <stdlib.h>
#endif
#include "inifile.loc"
#include "dynstr.h"
#include "dfn.h"
#include "supplio.h"

#include "suppldbg.h"

#ifdef RCS_Version
static char const rcsid[] = 
	"$Id: CFGI_CFI.C 1.5 2001/02/27 01:27:48 ska Exp ska $";
#endif

int cfgi_createFile(const char * const file)
{	char *fnam, *p;
	int rv;

	DBG_ENTER("cfgi_createFile", Suppl_inifile1)
	DBG_ARGUMENTS( ("fnam=\"%s\"", file) )

	chkHeap
	if(!file)		DBG_RETURN_I( CFG_ERR_MEM)

	if(cfgi_ini) {
		free(file);
		DBG_RETURN_I( CFG_ERR_ALREADY)
	}

	chkHeap
	if((p = dfnfilename(StrRepl(cfgi_fnam, (char *)file))) <= cfgi_fnam)
		DBG_RETURN_I( CFG_ERR_ARG)
	chkHeap

	/* create temporary file name in the same path as INI file itself */
	rv = *--p;
	*p = '\0';
	if(!(dfnstat(cfgi_fnam) & DFN_DIRECTORY))
		DBG_RETURN_I( CFG_ERR_USRHOME)
	if((fnam = dfnmktmp(cfgi_fnam, 0)) == 0)
		DBG_RETURN_I( CFG_ERR_MEM)
	*p = rv;

	chkHeap
	if((cfgi_ini = Fxopen(fnam, "wt")) == 0) {
		unlink(fnam);
		rv = CFG_ERR_OPEN;
		goto ret1;
	}

	chkHeap
	rv = CFG_ERR_NONE;
	cfgi_nlwritten = 1;		/* needn't to append a '\n' */
	Fxinfo(cfgi_ini)->sea_istmp = 1;	/* if something fails --> remove */

ret1:
	chkHeap
	free(fnam);
	chkHeap

	DBG_RETURN_I( rv)
}
