/* open-po - search for .po file along search path list and open for reading
   Copyright (C) 1995 Software Foundation, Inc.
   Written by Ulrich Drepper <drepper@gnu.ai.mit.edu>, April 1995.

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

This program 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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.  */

#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#include <errno.h>
#include <stdio.h>
#include <sys/types.h>

#ifdef STDC_HEADERS
# include <stdlib.h>
#endif

#if defined STDC_HEADERS || HAVE_STRING_H
# include <string.h>
#else
# include <strings.h>
#endif

#include "error.h"
#include "system.h"

#include <libintl.h>

#define _(str) gettext (str)

#ifndef errno
extern int errno;
#endif

/* Prototypes for helper functions.  */
extern char *xstrdup __P ((const char *string));

/* Open the input file with the name INPUT_NAME.  The ending .po is added
   if necessary.  If INPUT_NAME is not an absolute file name and the file is
   not found, the list of directories in INPUT_PATH_LIST is searched.  */
FILE *
open_po_file (input_name, file_name)
     const char *input_name;
     char **file_name;
{
  FILE *ret_val;
  size_t len;

  if (strcmp (input_name, "-") == 0)
    {
      *file_name = xstrdup (_("<stdin>"));
      return stdin;
    }

  /* We have a real name for the input file.  First look for in the
     current directory.  If not found and the name does not is a
     absolute file name look through the input path.  */
  ret_val = fopen (input_name, "r");
  if (ret_val != NULL)
    {
      *file_name = xstrdup (input_name);
      return ret_val;
    }

  len = strlen (input_name);
  if (len <= 3 || strcmp (input_name + len - 3, ".po") != 0)
    {
      asprintf (file_name, "%s.po", input_name);
      if (*file_name == NULL)
	error (EXIT_FAILURE, errno, _("error while constructing file name"));

      ret_val = fopen (*file_name, "r");
      if (ret_val != NULL)
	return ret_val;

      free (*file_name);
    }

  /* File does not exist.  */
  *file_name = xstrdup (input_name);
  errno = ENOENT;
  return NULL;
}
