/*
    ####             #    #     # #
    #   #            #    #       #          The FreeWare C library for
    #   #  ##   ###  #  # #     # ###             RISC OS machines
    #   # #  # #     # #  #     # #  #   ___________________________________
    #   # ####  ###  ##   #     # #  #
    #   # #        # # #  #     # #  #    Please refer to the accompanying
    ####   ### ####  #  # ##### # ###    documentation for conditions of use
    ________________________________________________________________________

    File:    Serial.c.NZPWOnRec
    Author:  Copyright  1993 Jason Howat
    Version: 1.00 (21 Nov 1993)
    Purpose: Provide a handler to modify a pollword on reception of a
             character on the serial port.
*/

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

#include "Desk.Core.h"
#include "Desk.SWI.h"
#include "Desk.Error.h"
#include "Desk.Serial.h"


static unsigned *Desk_serial__RMAblock = NULL;
static void *Desk_serial__pollword = NULL;
static const unsigned Desk_serial__insvcode[] = {0xe92d4002,
                                            0xe3c11102,
                                            0xe3510001,
                                            0x059f1004,
                                            0x058c1000,
                                            0xe8fd8002};

void Desk_Serial__NZPWORRemove(void);


void Desk_Serial_NonZeroPollWordOnReceive(int Desk_pollword_value,
                                          void *pollword)
{
  Desk_Error_CheckFatal(SWI(4, 3, Desk_SWI_OS_Module + Desk_XOS_Bit, 6, 0, 0, 32,
                                      /* TO */ NULL, NULL, &Desk_serial__RMAblock));

  if(Desk_pollword_value == 0)
    Desk_pollword_value = 1;

  memcpy(Desk_serial__RMAblock, Desk_serial__insvcode, 24);
  Desk_serial__RMAblock[6] = Desk_pollword_value;

  Desk_Error_CheckFatal(SWI(3, 0, Desk_SWI_OS_Claim + Desk_SWI_XOS_Bit, 0x14, Desk_serial__RMAblock,
                                                              pollword));
  Desk_serial__pollword = pollword;

  atexit(Desk_Serial__NZPWORRemove);
}

void Desk_Serial__NZPWORRemove(void)
{
  Desk_Error_CheckFatal(SWI(3, 0, Desk_SWI_OS_Release + Desk_SWI_XOS_Bit,
                                     0x14, Desk_serial__RMAblock, Desk_serial__pollword));
  Desk_Error_CheckFatal(SWI(3, 0, Desk_SWI_OS_Module + Desk_SWI_XOS_Bit, 7, 0,
                                                             Desk_serial__RMAblock));
}
