/*
   riscosname.c --- translate filename extensions if necessary

   Copyright (C) 1998 Jakob Stoklund Olesen
   You may freely use and distribute this file.
 */

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

/* Check if a file exists. */
static int
isfile (const char *name)
{
  _kernel_osfile_block block;

  /* OS_File 5 reads directory info. r0 is returned or <0 for error */
  return _kernel_osfile (5, name, &block) == 1;
  /* r0 = 1 means file */
}

/* Check if a directory exists. */
static int
isdir (const char *name)
{
  _kernel_osfile_block block;

  /* OS_File 5 reads directory info. r0 is returned or <0 for error */
  return _kernel_osfile (5, name, &block) == 2;
  /* r0 = 2 means directory */
}

/* Buffer for returning names from riscos_*_name() */
static char name_buffer[1024];

/* Translate a filename for reading. The last occurrence of . or / is
   swapped if necessary to point to an existing file. If the name is
   altered a copy is returned in a static buffer which is valid until the
   next riscos_*_name() call. Otherwise the pointer given is returned.
 */
const char *
riscos_input_name (const char *fn)
{
  const char *p1;
  char *p2, *ext;

  if (fn == NULL || isfile (fn))
    return fn;

  /* Copy fn into buffer and find the last ext-sep-char */
  ext = NULL;
  for (p1 = fn, p2 = name_buffer;
       *p1 && p2 - name_buffer < 1024; p1++, p2++)
    {
      *p2 = *p1;
      if (*p2 == '.' || *p2 == '/')
	ext = p2;
    }
  /* If there was no extension or name was too long just return fn */
  if (ext == NULL || p2 >= name_buffer + 1024)
    return fn;

  /* terminate the buffer */
  *p2++ = 0;

  /* swap the extension */
  *ext = *ext == '.' ? '/' : '.';

  return isfile (name_buffer) ? name_buffer : fn;
}

/* Translate the extension separator for a file to be written. If the directory to hold the file does not exist, the last . is changed to a /. A copy of fn is returned if it was changed. */

const char *
riscos_output_name (const char *fn)
{
  char *ext;

  if (fn == NULL || strlen (fn) >= 1024)
    return fn;

  strcpy (name_buffer, fn);

  /* find the extension separator. Only . is recognised */
  ext = strrchr (name_buffer, '.');
  if (ext == NULL)
    return fn;
  *ext = 0;

  /* If the target directory existsuse it, otherwise use / */
  if (isdir (name_buffer))
    return fn;
  else
    {
      *ext = '/';
      return name_buffer;
    }
}
