#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/times.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>

#include "riscos.h"
#include "module-ddeutils.h"

bool DDEUtils::SWI (unsigned int swinum, bool xbit)
{
  switch (swinum)
    {
    case DDEUtils_Prefix: Prefix (); break;
    case DDEUtils_SetCLSize: SetCLSize (); break;
    case DDEUtils_SetCL: SetCL (); break;
    case DDEUtils_GetCLSize: GetCLSize (); break;
    case DDEUtils_GetCl: GetCl (); break;
    case DDEUtils_ThrowbackRegister: ThrowbackRegister (); break;
    case DDEUtils_ThrowbackUnRegister: ThrowbackUnRegister (); break;
    case DDEUtils_ThrowbackStart: ThrowbackStart (); break;
    case DDEUtils_ThrowbackSend: ThrowbackSend (); break;
    case DDEUtils_ThrowbackEnd: ThrowbackEnd (); break;
    case DDEUtils_ReadPrefix: ReadPrefix (); break;
    default:
      return false;
      break;
    }
  return true;
}

void DDEUtils::Prefix (void)
{
  char *buf = (char *) READ_REG (0);
  if (dde_prefix != NULL)
    {
      free (dde_prefix);
      dde_prefix = NULL;
    }
  if (buf != 0)
    {
      dde_prefix = strdup (buf);
    }
}

void DDEUtils::SetCLSize (void)
{
  if (dde_cmd_line)
    free (dde_cmd_line);
  dde_cmd_line_size = READ_REG (0);
  if (dde_cmd_line_size == 0)
    dde_cmd_line = NULL;
  else
    dde_cmd_line = (char *) malloc (dde_cmd_line_size);
}

void DDEUtils::SetCL (void)
{
  char *cmdline = (char *) READ_REG (0);
  strcpy (dde_cmd_line, cmdline);
}

void DDEUtils::GetCLSize (void)
{
  if (dde_cmd_line == NULL)
    WRITE_REG (0, 0);
  else
    WRITE_REG (0, strlen (dde_cmd_line) + 1);
}

void DDEUtils::GetCl (void)
{
  char *dst = (char *) READ_REG (0);
  strcpy (dst, dde_cmd_line);
}

void DDEUtils::ThrowbackRegister (void)
{
}

void DDEUtils::ThrowbackUnRegister (void)
{
}

void DDEUtils::ThrowbackStart (void)
{
}

void DDEUtils::ThrowbackSend (void)
{
}

void DDEUtils::ThrowbackEnd (void)
{
}

void DDEUtils::ReadPrefix (void)
{
  if (dde_prefix == NULL)
    WRITE_REG (0, 0);
  else
    WRITE_REG (0, (uint32_t) dde_prefix);
}
