/*
  Unix OS interface
  
  Almost pure ANSI library, but we use bcopy rather than memcpy since
  SunOS 4.1.1 is missing memcpy and most X11 platforms fake bcopy.
*/

#include "os.h"

#include <ctype.h>
#include <stdio.h>

#if STDC_HEADERS
#include <stdlib.h>
#include <string.h>
#include <time.h>
#else
#if HAVE_MEMORY_H
#include <memory.h>
#endif
#if HAVE_STRINGS_H
#include <strings.h>
#endif
#if HAVE_TIME_H
#include <time.h>
#endif
#endif

#ifndef SEEK_SET
#define SEEK_SET 0
#endif
#ifndef SEEK_END
#define SEEK_END 2
#endif

filep os_open_read(const char *name)
{
  return (filep) fopen(name, "r");
}

filep os_wild_read(const char *name)
{
  return os_open_read(name);
}

filep os_open_write(const char *name)
{
  return (filep) fopen(name, "w");
}

filep os_open_append(const char *name)
{
  filep res = (filep) fopen(name, "a");
  return res ? res : os_open_write(name);
}

int os_close(filep f)
{
  return fclose(f);
}

int os_seek_fore(filep f, long_word off)
{
  return fseek(f, off, SEEK_SET);
}

int os_seek_back(filep f, long_word off)
{
  return fseek(f, off, SEEK_END);
}

int os_read(void *buff, size_t size, int count, filep f)
{
  return fread(buff, size, count, f);
}

int os_write(void *buff, size_t size, int count, filep f)
{
  return fwrite(buff, size, count, f);
}

void os_exit(int e)
{
  exit(e);
}

void os_mcpy(void *d, void *s, size_t n)
{
#if HAVE_MEMCPY
  memcpy(d, s, n);
#else
#if HAVE_BCOPY
  bcopy(s, d, n);
#else
  size_t i;
  for(i = 0; i < n; ++i)
    ((char *) d)[i] = ((char *) s)[i];
#endif
#endif
}

void os_mset(char *p, size_t n, char v)
{
#if HAVE_MEMSET
  memset(p, v, n);
#else
  size_t i;
  for(i = 0; i < n; ++i)
    p[i] = v;
#endif
}

void os_strcpy(char *d, const char *s)
{
  strcpy(d, s);
}

void os_strcat(char *d, const char *s)
{
  strcat(d, s);
}

int os_strlen(const char *s)
{
  return strlen(s);
}

int os_strcmp(const char *s, const char *t)
{
  return strcmp(s, t);
}

void *os_alloc(size_t n)
{
  return malloc(n);
}

void os_free(void *p)
{
  free(p);
}

void *os_realloc(void *p, size_t n)
{
  return realloc(p, n);
}

char os_lower(char c)
{
  return tolower(c);
}

long_word os_time(void)
{
  return (long_word) time(0);
}

char *os_leaf(char *s)
{
  return s;
}

void os_patch_save(char *s)
{
}

int os_strpos(char *s, char c)
{
#if HAVE_STRCHR
  char *t = strchr(s, c);
  return t ? t - s : -1;
#else
  char *t = s;
  while(*t && *t != c) ++t;
  return *t == c ? t - s : -1;
#endif
}

