/* Copyright (C) Acorn Computers Ltd 1994 */

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

#include "kernel.h"
#include "swis.h"
#include "wimp.h"
#include "wimplib.h"
#include "toolbox.h"

#include "window.h"
#include "utils.h"
#include "hyper.h"

/* return contents of address, that may not be word aligned */

static unsigned int contents_of(char *a)
{
   unsigned char *ad = (unsigned char *) a;
   unsigned int v = (((*(ad+3)) <<24) +
          ((*(ad+2)) <<16) +
          ((*(ad+1)) <<8 ) + *ad);

   return v;
}

#define SQUASH  0x48535153                /* SQSH */

/* to save space we allow compressed draw files */

int decompress(char **file, int *size)
{
   if (contents_of(*file) == SQUASH) {
      /* it's squashed */

      char *wkspc=0;
      int ss,q;
      char *s;
      q = contents_of((*file)+4);        /* size */
      s = malloc(q);
      if (!s) return FAILED;

      if (_swix(Squash_Decompress,_IN(0) | _IN(1)  | _OUT(0),
              8,(*size)-20,&ss)) return FAILED;

      wkspc = malloc(ss);
      if ((!wkspc) || (_swix(Squash_Decompress,_IN(0) | _IN(1) |_IN(2) |
                            _IN(3) |_IN(4) |_IN(5),
                            4,wkspc,(*file)+20,(*size)-20,s,q))) {
          free(s);
          if (wkspc) free (wkspc);
          return FAILED;
      }
      free(wkspc);
      free(*file);

      *file =s;
      *size = q;

   }
   return SUCCESS;
}

int file_size(char *name)
{
  _kernel_swi_regs regs;
  regs.r[0] = 17;
  regs.r[1] = (int) name;

  if(_kernel_swi(OS_File,&regs,&regs)) regs.r[4] = 0;

  return regs.r[4];
}


_kernel_oserror * file_load(char *name, char *add)
{
  _kernel_swi_regs regs;
  regs.r[0] = 16;
  regs.r[1] = (int) name;
  regs.r[2] = (int) add;
  regs.r[3] = 0;

  return (_kernel_swi(OS_File,&regs,&regs));
}

void CLG(void)
{
   _swix(0x110,0);
}


static char obj__name[16];

char *object_name(ObjectId id)
{
    if(toolbox_get_template_name(0,id,obj__name,16,0)) return NULL;
    return obj__name;
}

int is_object(ObjectId id,char *name)
{
    if(toolbox_get_template_name(0,id,obj__name,16,0)) return 1;
    return ((int) strcmp(obj__name,name));

}

char * lookup_token(char *tag)
{
    _kernel_swi_regs regs;
    regs.r[0] = (int) &mbl;
    regs.r[1] = (int) tag;
    regs.r[2] = 0;

    if (_kernel_swi(MessageTrans_Lookup,&regs,&regs)) return 0;
    else return (char *) regs.r[2];

}

/* just puts up an error box - used when mallocs fail */

void warn_about_memory(void)
{
   _kernel_oserror e = {0,0};

   strcpy(e.errmess,lookup_token("NoMem"));
   wimp_report_error(&e,0,0);
}
