/**************************************************************************//**
 * @file     Retarget.c
 * @brief    This file contains re-implementations of functions whose
 *           C library implementations rely on semihosting.
 * @version
 * @date     25 March 2013
 *
 * @note
 *
 ******************************************************************************/
/* Copyright (c) 2011 - 2013 ARM LIMITED

   All rights reserved.
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
   - Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
   - Neither the name of ARM nor the names of its contributors may be used
     to endorse or promote products derived from this software without
     specific prior written permission.
   *
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE.
   ---------------------------------------------------------------------------*/

#include <stdio.h>
#include "Serial.h"



#define TRUE 1
#define FALSE 0



/*
** Importing __use_no_semihosting ensures that our image doesn't link
** with any C Library code that makes direct use of semihosting.
*/

#ifdef __MICROLIB
#pragma import(__use_no_semihosting)
#endif

/*
** Retargeted I/O
** ==============
** The following C library functions make use of semihosting
** to read or write characters to the debugger console: fputc(),
** fgetc(), and _ttywrch().  They must be retargeted to write to
** the model's UART.  __backspace() must also be retargeted
** with this layer to enable scanf().  See the Compiler and
** Libraries Guide.
*/

/*
** These must be defined to avoid linking in stdio.o from the
** C Library
*/

struct __FILE { int handle;   /* Add whatever you need here */};
typedef struct __FILE FILE;
FILE __stdout;
FILE __stdin;
FILE __stderr;

/*
** __backspace must return the last char read to the stream
** fgetc() needs to keep a record of whether __backspace was
** called directly before it
*/
int last_char_read;
int backspace_called;


int fgetc(FILE *f)
{
    unsigned char tempch;
    tempch = SER_GetChar();
    last_char_read = (int)tempch;       /* backspace must return this value */
    return tempch;
}


int fputc(int ch, FILE *f)
{
    unsigned char tempch = ch;
    if (tempch == 10) SER_PutChar(13);
    SER_PutChar(tempch);
    return ch;
}

int fclose(FILE *f) {
	return (0);
}

int fseek (FILE *f, long nPos, int nMode) {
	return 0;
}

int fflush (FILE *f) {
	return 0;
}

void _ttywrch(int ch)
{
    unsigned char tempch = ch;
    if (tempch == 10) SER_PutChar(13);
    SER_PutChar(tempch);
}

/*
** The effect of __backspace() should be to return the last character
** read from the stream, such that a subsequent fgetc() will
** return the same character again.
*/

int __backspace(FILE *f)
{
    backspace_called = TRUE;
    return 1;
}

#if defined ( __GNUC__ )
#define SioWrite        _write
#define SioRead         _read

/* File descriptor */
#define STDIN           (0)
#define STDOUT          (1)
#define STDERR          (2)

#define SIORW_SUCCESS   (0)
#define SIORW_ERROR     (-1)
#define SIORW_FLAG_OFF  (0)
#define SIORW_FLAG_ON   (1)

#ifndef char_t
typedef char            char_t;
#endif

int32_t SioWrite(int32_t file_no, char_t * buffer, int32_t writing_b)
{
    uint32_t offset;

    if ((STDOUT == file_no) || (STDERR == file_no))
    {
        for (offset = 0; offset < writing_b; offset++)
        {
            /* Writing in buffer converting linefeed code */
            if ('\n' == *(buffer + offset))
            {
                if (0 == offset)
                {
                    SER_PutChar('\r');
                }
                else
                {
                    if (*(buffer + offset - 1) != '\r')
                    {
                        SER_PutChar('\r');
                    }
                }
                SER_PutChar('\n');
            }
            else
            {
                SER_PutChar(*(buffer + offset));
            }
        }
        return (int32_t)offset;
    }

    return SIORW_ERROR;     /* File number error */
}

int32_t SioRead(int32_t file_no, char_t * buffer, int32_t reading_b)
{
    char_t         char_mem;
    char_t         SP_char;
    uint32_t       offset;
    static int32_t sjis_flg = SIORW_FLAG_OFF;

    if (STDIN == file_no)
    {
        for (offset = 0; offset < reading_b; )
        {
            /* Reading receiving data */
            char_mem = SER_GetChar();

            if (0xFF == char_mem)   /* -1 is returned when it is receiving data error */
            {
                return SIORW_ERROR;
            }

            if (SIORW_FLAG_ON == sjis_flg)
            {
                sjis_flg = SIORW_FLAG_OFF;
                _write(STDOUT, &char_mem, 1);
                *(buffer + offset) = char_mem;
                offset++;
            }
            else if ((0x20 <= char_mem) && (char_mem <= 0x7E))
            {
                /* Data possible to display */
                _write(STDOUT, &char_mem, 1);
                *(buffer + offset) = char_mem;
                offset++;
            }
            else if ('\b' == char_mem)      /* BS process */
            {
                if (offset > 0)
                {
                    SP_char = 0x20;
                    _write(STDOUT, &char_mem, 1);
                    _write(STDOUT, &SP_char, 1);
                    _write(STDOUT, &char_mem, 1);
                    offset--;

                }
                else
                {
                    if (reading_b == 1)
                    {
                        SP_char = 0x20;
                        _write(STDOUT, &char_mem, 1);
                        _write(STDOUT, &SP_char, 1);
                        _write(STDOUT, &char_mem, 1);
                        *(buffer + offset) = char_mem;
                        offset++;
                    }
                }
            }
            else if ('\r' == char_mem)      /* CR process */
            {
                *(buffer + offset) = '\n';
                _write(STDOUT, buffer + offset, 1);
                offset++;
                break;
            }
            /* Japanese SJIS ? */
            else if (((char_mem >= 0x80) && (char_mem < 0xA0)) || ((char_mem >= 0xE0) && (char_mem < 0xFE)))
            {
                /* Data possible to display */
                _write(STDOUT, &char_mem, 1);
                *(buffer + offset) = char_mem;
                offset++;
                sjis_flg = SIORW_FLAG_ON;
            }
            /* Character cord out of the support */
            else
            {
                /* Do Nothing */
            }
        }
        return (int32_t)offset;
    }

    return SIORW_ERROR;     /* File number error */
}

#endif  /* __CNUC__ */

/*
** Exception Signaling and Handling
** ================================
** The C library implementations of ferror() uses semihosting directly
** and must therefore be retargeted.  This is a minimal reimplementation.
** _sys_exit() is called after the user's main() function has exited.  The C library
** implementation uses semihosting to report to the debugger that the application has
** finished executing.
*/
#if defined ( __CC_ARM )
int ferror(FILE *f)
{
    return EOF;
}
#endif

void _sys_exit(int return_code)
{
    while(1);
}

void _init(void)
{
	return;
}

void _fini(void)
{
	return;
}

#if defined ( __GNUC__ )
#pragma weak __libc_init_array
void __libc_init_array(void)
{
	return;
}

#pragma weak __libc_fini_array
void __libc_fini_array(void)
{
	return;
}

#pragma weak _exit
void _exit (int status)
{
	return;
}

#pragma weak __exit
void __exit (int status)
{
	return;
}


/*
	Library Generatorにおいて、標準関数を組み込むために
	関数呼び出し処理を組み込む
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void gnu_dummy_routine(void)
{
	int8_t *blk1;
	int8_t *blk2;
	char_t string[]="test";
	uint32_t a,b,c;

    printf("gnu_dummy_routine\n");

	blk1 = malloc(256);
	blk2 = calloc(1, 256);

	(void)memset(blk1, 0, 256);
	(void)memset(blk2, 0, 256);
    (void)strcpy(blk2, string);
    (void)strncpy(blk2, string, 5);
    (void)strcat(blk2, string);
	(void)sprintf(blk2, "%s\n", string);

	(void)memcpy(blk1, blk2, strlen(string));

    if(strcmp(blk1, blk2) != 0)
	{
		printf("error1\n");
	}
    if(strncmp(blk1, blk2, 256) != 0)
	{
		printf("error2\n");
	}

	free(blk1);
	free(blk2);
}

#endif  /* __CNUC__ */

