/* Copyright (C) 2000-2004 Damir Zucic */

/*=============================================================================

				create_log_file.c

Purpose:
	Try to create a new log file,  opened for writting.  First try to
	create log file in the current working directory. If this attempt
	fails,  try to create  the log file in the  users home directory.

Input:
	(1) Input file name.
	(2) The content of environment variable HOME may be used.

Output:
	Return value.

Return value:
	(1) File pointer, on success.
	(2) NULL on failure.

Notes:
	(1) No error messages.

========includes:============================================================*/

#include <stdio.h>

#include <string.h>
#include <stdlib.h>

#include "defines.h"

/*======try to create log file:==============================================*/

FILE *CreateLogFile_ (char *log_file_nameP)
{
static FILE	*fileP;
static char	*env_valueP;
char		path_nameA[STRINGSIZE];
int		n;

/* The first attempt: */
if ((fileP = fopen (log_file_nameP, "w")) != NULL) return fileP;

/* If this point is reached, the first attempt failed! */

/* Prepare the file name pointer. If the first character is slash, skip it! */
if (*log_file_nameP == '/') log_file_nameP++;

/* The second attempt (using environment variable HOME): */
if ((env_valueP = getenv ("HOME")) != NULL)
	{
	/* Copy the value of the environment variable HOME: */
	strncpy (path_nameA, env_valueP, STRINGSIZE - 1);
	path_nameA[STRINGSIZE - 1] = '\0';

	/* The last character should be slash: */
	n = (int) strlen (path_nameA) - 1;
	if (path_nameA[n] != '/') strcat (path_nameA, "/");

	/* Concatename the file name to directory name: */
	n = STRINGSIZE - (int) strlen (path_nameA) - 1;
	strncat (path_nameA, log_file_nameP, n);
	path_nameA[STRINGSIZE - 1] = '\0';

	/* The second attempt to open file: */
	if ((fileP = fopen (path_nameA, "w")) != NULL) return fileP;
	}

/* If this point is reached, both attempts failed; return NULL: */
return NULL;
}

/*===========================================================================*/


