/*

$Id: ftrunc,v 1.8 2001/03/31 14:34:29 joseph Exp $

*/

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

#include "swis.h"

#include "ftrunc.h"

void file_truncate(const char *filename, long int len)
{
  int handle;

  if (_swix(OS_Find, _INR(0,1)|_OUT(0), 0xc4, filename, &handle) || !handle)
    return;
  _swix(OS_Args, _INR(0,2), 3, handle, len);
  _swix(OS_Find, _INR(0,1), 0, handle);
}

bool file_exists(const char *file)
{
  int objtype;

  return !(_swix(OS_File, _INR(0,1)|_OUT(0), 5, file, &objtype) || !objtype);
}

int file_size(const char *file)
{
  int size;
  int objtype;

  if ( _swix(OS_File, _INR(0,1)|_OUT(0)|_OUT(4), 5, file, &objtype, &size) || objtype == 0 )
    return -1;

  return size;
}


_kernel_oserror *file_rename(const char *from, const char *to)
{
  _kernel_oserror *e;
  
  e = _swix(OS_FSControl, _INR(0,2), 25, from, to);
  
  /* if that failed, we should really try a move instead */
  
  return e;
}

static _kernel_oserror *file_createdir(const char *name)
{
  return _swix(OS_File, _INR(0,1), 8, name);
}
  

/* ensures the directory name given (and all the path elements
 * above it) exists. */
_kernel_oserror *file_createdirs(const char *dirname)
{
  _kernel_oserror *e;
  char *dir = malloc(strlen(dirname) + 1);
  if (dir)
  {
    char *p;
    strcpy(dir, dirname);
    p = strchr(dir, '.');
    while (p)
    {
      *p = '\0';
      e = file_createdir(dir);
      if (e)
      {
        free(dir);
        return e;
      }
      *p = '.';
      p = strchr(p + 1, '.');
    }
  }
  free(dir);
  
  return file_createdir(dirname);
}
