/* Additional support functions for dcraw on RISC OS
   Based on the work by T. Milius */

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

#define M_PI 3.141592654
#define M_SQRT1_2 0.707106781
#define OS_FSControl 0x29
#define OS_File 0x08

/* Normally defined in sys/types.h */
typedef int ssize_t;

int isatty(int dummy)
{

/* No output to taskwindow. */
return 1;
}

size_t strnlen(const char *s, size_t maxlen) {
  int i;

  i=0;
  while(*(s+i) != '\0' && maxlen) {
    i++;
    maxlen--;
  }
  return(i);
}

int strncasecmp(const char *s1, const char *s2, size_t n) {
  unsigned char u1, u2;

  while(n--) {
    u1=(unsigned char) *s1++;
    u2=(unsigned char) *s2++;
    if(toupper(u1) != toupper(u2))
      return(toupper(u1)-toupper(u2));
    if(u1=='\0')
      break;
  }
  return(0);
}

int strcasecmp(const char *s1, const char *s2) {

  while(toupper(*s1)==toupper(*s2)) {
    if(*s1++=='\0')
      return(0);
    s2++;
  }
  return(toupper(*s1)-toupper(*s2));
}

/* get current work directory */
char *getcwd(char *buf, size_t size) {
  char *fs;
  _kernel_swi_regs regs;

  /* First find current filesystem */
  if ((fs=getenv("FileSwitch$CurrentFilingSystem")) == NULL) {
    *buf='\0';
    return buf;
  }

  /* Now find currently selected directory */
  regs.r[0]=54;
  regs.r[1]=(int) buf;
  regs.r[2]=0;
  regs.r[3]=(int) fs;
  regs.r[5]=80;
  _kernel_swi(OS_FSControl, &regs, &regs);
  if(regs.r[1]==0) {
    *buf='\0';
    return buf;
  }
  return buf;
}

/* Swap even and odd Bytes */
void swab(const void *from, void *to, ssize_t n) {
  int offset;

  if (n <= 0) return;

  for (offset=0; offset < n; offset+=2) {
    *(((char *) to) + offset)=*(((char *) from) + offset + 1);
    *(((char *) to) + offset + 1)=*(((char *) from) + offset);
  }
}

int fileno(FILE *file) {

  if (file == stdin) return 0;
  if (file == stdout) return 1;
  if (file == stderr) return 2;
  return 3;
}

/* Set the type of a specified file */
int set_file_type(char *file_name, int file_type) {
  _kernel_oserror *os_error;
  _kernel_swi_regs regs;

  regs.r[0]=18;
  regs.r[1]=(int) file_name;
  regs.r[2]=file_type & 0xFFF;
  if ((os_error=_kernel_swi(OS_File, &regs, &regs)) != NULL) {
    return 1;
  } else {
    return 0;
  }
}
