/*
 * Copyright (C) 2020-2021 Aloysius Indrayanto
 *
 * This file is part of the eCxx library, see LICENSE file for the license details.
 */

/*
 * ----------------------------------------------------------------------------------
 * The code in this file is copied (with a slight modifications) from:
 *     libc_replacements.cpp - replaces libc functions with functions from
 *                             Espressif SDK
 * ----------------------------------------------------------------------------------
 * Copyright (C) 2015 Ivan Grokhotkov. All rights reserved.
 *
 * This file is part of the esp8266 core for Arduino environment.
 *
 * This library is free software; you can redistribute it and/or modify it under the
 * terms of the GNU Lesser General Public License as published by the Free Software
 * Foundation; either version 2.1 of the License, or (at your option) any later
 * version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License along
 * with this library; if not, write to the Free Software Foundation, Inc., 51
 * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
 * ----------------------------------------------------------------------------------
 */


#include <unistd.h>
#include <sys/stat.h>

#include "CoreLib.h"
#include "CoreSys.h"


extern "C" {


extern void _exit(int /*status*/)
{ abort(); }


extern int ICACHE_RAM_ATTR _open_r(_reent*, const char* /*ptr*/, int /*mode*/)
{ return 0; }


extern int ICACHE_RAM_ATTR _close_r(_reent*, int /*file*/)
{ return 0; }


extern int ICACHE_RAM_ATTR _fstat_r(_reent*, int /*file*/, struct stat* st)
{
    st->st_mode = S_IFCHR;
    return 0;
}


extern int ICACHE_RAM_ATTR _lseek_r(_reent*, int /*file*/, int /*ptr*/, int /*dir*/)
{ return 0; }


extern int ICACHE_RAM_ATTR _read_r(_reent*, int /*file*/, char* /*ptr*/, int /*len*/)
{ return 0; }


extern int ICACHE_RAM_ATTR _write_r(_reent*, int file, char* ptr, int len)
{
    int pos = len;

    if(file == STDOUT_FILENO) {
        while(pos--) ets_putc(*ptr++);
    }

    return len;
}


extern int ICACHE_RAM_ATTR _putc_r(_reent*, int c, FILE* file) __ECXX_ATTR_WEAK;
extern int ICACHE_RAM_ATTR _putc_r(_reent*, int c, FILE* file)
{
    if(file->_file == STDOUT_FILENO) {
        ets_putc(c);
        return c;
    }

    return EOF;
}


extern int ICACHE_RAM_ATTR putchar(int c)
{
    ets_putc(c);
    return c;
}


extern int ICACHE_RAM_ATTR puts(const char* str)
{
    while(*str) ets_putc(*str++);
    ets_putc('\n');

    return 1;
}


extern int atexit( void(*)() ) __ECXX_ATTR_WEAK;
extern int atexit( void(*)() )
{ return 0; }


} // extern "C"

