{

  base64_codesafe_decoding_table = (char*) malloc(256);

    for (int i = 0; i < 64; i++)
        base64_codesafe_decoding_table[(unsigned char) base64_codesafe_encoding_table[i]] = i;
}

/*
 *
 * All rights reserved.
 *
 *
 *
 */

#include "UNIV.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <sstream>
#include <iosfwd>
#include <iomanip>
#include "pcre.h"
#include "SchemeFFI.h"
#include "SchemePrivate.h"

#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <AppKit/AppKit.h>
#else
#include <time.h>
#endif

#ifdef _WIN32
#include <malloc.h>
#include <Windows.h>

enum Windows_Color_Convert
{
    Black   = 0,
    Red     = FOREGROUND_RED,
    Green   = FOREGROUND_GREEN,
    Yellow  = FOREGROUND_RED   | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
    Blue    = FOREGROUND_BLUE  | FOREGROUND_INTENSITY,
    Magenta = FOREGROUND_RED   | FOREGROUND_BLUE,
    Cyan    = FOREGROUND_GREEN | FOREGROUND_BLUE,
    White   = FOREGROUND_RED   | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY
};

enum Windows_BGColor_convert
{
    BGBlack   = 0,
    BGRed     = BACKGROUND_RED,
    BGGreen   = BACKGROUND_GREEN,
    BGYellow  = BACKGROUND_RED   | BACKGROUND_GREEN | BACKGROUND_INTENSITY,
    BGBlue    = BACKGROUND_BLUE,
    BGMagenta = BACKGROUND_RED   | BACKGROUND_BLUE,
    BGCyan    = BACKGROUND_GREEN | BACKGROUND_BLUE,
    BGWhite   = BACKGROUND_RED   | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY,
};

int WINDOWS_COLORS[] = { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White };
int WINDOWS_BGCOLORS[] = { BGBlack, BGRed, BGGreen, BGYellow, BGBlue, BGMagenta, BGCyan, BGWhite };

#endif

static char base64_codesafe_encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                                                'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                                                'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                                                'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                                                'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                                                'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                                                'w', 'x', 'y', 'z', '0', '1', '2', '3',
                                                '4', '5', '6', '7', '8', '9', '_', '-'};

static char base64_std_encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                                           'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                                           'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                                           'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                                           'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                                           'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                                           'w', 'x', 'y', 'z', '0', '1', '2', '3',
                                           '4', '5', '6', '7', '8', '9', '+', '/'};

static char *base64_std_decoding_table = NULL;
static char *base64_codesafe_decoding_table = NULL;
static int _base64_mod_table[] = {0, 2, 1};

void base64_std_build_decoding_table() {

  base64_std_decoding_table = (char*) malloc(256);

    for (int i = 0; i < 64; i++)
        base64_std_decoding_table[(unsigned char) base64_std_encoding_table[i]] = i;
}

void base64_codesafe_build_decoding_table()

void base64_std_cleanup() {
    free(base64_std_decoding_table);
}

void base64_codesafe_cleanup() {
    free(base64_codesafe_decoding_table);
}

EXPORT char* cname_encode(char *data, size_t input_length, size_t *output_length)
{
    *output_length = 4 * ((input_length + 2) / 3);

    char *encoded_data = (char*) malloc(*output_length+1);
    encoded_data[*output_length] = 0;
    if (encoded_data == NULL) return NULL;

    for (unsigned i = 0, j = 0; i < input_length;) {

        uint32_t octet_a = i < input_length ? data[i++] : 0;
        uint32_t octet_b = i < input_length ? data[i++] : 0;
        uint32_t octet_c = i < input_length ? data[i++] : 0;

        uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

        encoded_data[j++] = base64_codesafe_encoding_table[(triple >> 3 * 6) & 0x3F];
        encoded_data[j++] = base64_codesafe_encoding_table[(triple >> 2 * 6) & 0x3F];
        encoded_data[j++] = base64_codesafe_encoding_table[(triple >> 1 * 6) & 0x3F];
        encoded_data[j++] = base64_codesafe_encoding_table[(triple >> 0 * 6) & 0x3F];
    }

    for (int i = 0; i < _base64_mod_table[input_length % 3]; i++) {
      encoded_data[*output_length - 1 - i] = 0; //'$';
    }

    return encoded_data;
}

EXPORT char* cname_decode(char *data, size_t input_length, size_t *output_length)
{
    if (base64_codesafe_decoding_table == NULL) base64_codesafe_build_decoding_table();

    char* d2 = NULL;
    // pad with $'s
    if (input_length % 4 != 0) {
      int lgthdiff = (4-(input_length % 4));
      char* d2 = (char*) malloc(input_length+lgthdiff);
      memcpy(d2,data,input_length);
      input_length = input_length+lgthdiff;
      for(int i=0;i<lgthdiff;i++) {
        d2[input_length-1-i] = '$';
      }
      data = d2;
    }

    if (input_length % 4 != 0) return NULL;
    *output_length = input_length / 4 * 3;
    if (data[input_length - 1] == '$') (*output_length)--;
    if (data[input_length - 2] == '$') (*output_length)--;

    char *decoded_data = (char*) malloc(*output_length+1);
    decoded_data[*output_length] = 0;
    if (decoded_data == NULL) return NULL;

    for (unsigned i = 0, j = 0; i < input_length;) {

        uint32_t sextet_a = data[i] == '$' ? 0 & i++ : base64_codesafe_decoding_table[unsigned(data[i++])];
        uint32_t sextet_b = data[i] == '$' ? 0 & i++ : base64_codesafe_decoding_table[unsigned(data[i++])];
        uint32_t sextet_c = data[i] == '$' ? 0 & i++ : base64_codesafe_decoding_table[unsigned(data[i++])];
        uint32_t sextet_d = data[i] == '$' ? 0 & i++ : base64_codesafe_decoding_table[unsigned(data[i++])];

        uint32_t triple = (sextet_a << 3 * 6)
        + (sextet_b << 2 * 6)
        + (sextet_c << 1 * 6)
        + (sextet_d << 0 * 6);

        if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
    }
    if (d2) free(d2);
    return decoded_data;
}

EXPORT char* base64_encode(const unsigned char *data, size_t input_length, size_t *output_length)
{
    *output_length = 4 * ((input_length + 2) / 3);

    char *encoded_data = (char*) malloc(*output_length+1);
    encoded_data[*output_length]=0;

    if (encoded_data == NULL) return NULL;

    for (unsigned i = 0, j = 0; i < input_length;) {

        uint32_t octet_a = i < input_length ? data[i++] : 0;
        uint32_t octet_b = i < input_length ? data[i++] : 0;
        uint32_t octet_c = i < input_length ? data[i++] : 0;

        uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

        encoded_data[j++] = base64_std_encoding_table[(triple >> 3 * 6) & 0x3F];
        encoded_data[j++] = base64_std_encoding_table[(triple >> 2 * 6) & 0x3F];
        encoded_data[j++] = base64_std_encoding_table[(triple >> 1 * 6) & 0x3F];
        encoded_data[j++] = base64_std_encoding_table[(triple >> 0 * 6) & 0x3F];
    }

    for (int i = 0; i < _base64_mod_table[input_length % 3]; i++)
        encoded_data[*output_length - 1 - i] = '=';

    return encoded_data;
}

EXPORT unsigned char* base64_decode(const char *data, size_t input_length, size_t *output_length)
{
    if (base64_std_decoding_table == NULL) base64_std_build_decoding_table();

    if (input_length % 4 != 0) return NULL;

    *output_length = input_length / 4 * 3;
    if (data[input_length - 1] == '=') (*output_length)--;
    if (data[input_length - 2] == '=') (*output_length)--;

    unsigned char *decoded_data = (unsigned char*) malloc(*output_length);
    if (decoded_data == NULL) return NULL;

    for (unsigned i = 0, j = 0; i < input_length;) {

        uint32_t sextet_a = data[i] == '=' ? 0 & i++ : base64_std_decoding_table[unsigned(data[i++])];
        uint32_t sextet_b = data[i] == '=' ? 0 & i++ : base64_std_decoding_table[unsigned(data[i++])];
        uint32_t sextet_c = data[i] == '=' ? 0 & i++ : base64_std_decoding_table[unsigned(data[i++])];
        uint32_t sextet_d = data[i] == '=' ? 0 & i++ : base64_std_decoding_table[unsigned(data[i++])];

        uint32_t triple = (sextet_a << 3 * 6)
        + (sextet_b << 2 * 6)
        + (sextet_c << 1 * 6)
        + (sextet_d << 0 * 6);

        if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
    }

    return decoded_data;
}

EXPORT bool rmatch(char* regex, const char* str)
{
  const char* data = str;
  char* pattern = regex;

  pcre *re;
  const char *error;
  int erroffset;

  re = pcre_compile(    pattern, /* the pattern */
                        0, /* default options */
                        &error, /* for error message */
                        &erroffset, /* for error offset */
                        NULL); /* use default character tables */

  int rc;
  int ovector[30];
  rc = pcre_exec(       re, /* result of pcre_compile() */
                        NULL, /* we didn’t study the pattern */
                        data, /* the subject string */
                        strlen(data), /* the length of the subject string */
                        0, /* start at offset 0 in the subject */
                        0, /* default options */
                        ovector, /* vector of integers for substring information */
                        30); /* number of elements (NOT size in bytes) */

  return (rc>=0) ? true : false;
}

//      rc = pcre_exec( re, /* result of pcre_compile() */
//                      NULL, /* we didn’t study the pattern */
//                      data, /* the subject string */
//                      strlen(data), /* the length of the subject string */
//                      0, /* start at offset 0 in the subject */
//                      60); /* number of elements (NOT size in bytes) */

//      // if failed to match return empty list

EXPORT int64_t rmatches(char* regex, char* str, char** results, int64_t maxnum)
    {
  char* data = str;
  char* pattern = regex;
        pcre *re;
        const char *error;
        int erroffset;
        re = pcre_compile(      pattern, /* the pattern */
                                0, /* default options */
                                &error, /* for error message */
                                &erroffset, /* for error offset */
                                NULL); /* use default character tables */

        // pointer to hold return results
        int rc;
        int ovector[60];
  int64_t num=0;

        while(true) {
            rc = pcre_exec(     re, /* result of pcre_compile() */
                                NULL, /* we didn’t study the pattern */
                                data, /* the subject string */
                                strlen(data), /* the length of the subject string */
                                0, /* start at offset 0 in the subject */
                                0, /* default options */
                                ovector, /* vector of integers for substring information */
                                60); /* number of elements (NOT size in bytes) */

            if(rc<1 || num>=maxnum) {
        return num;
            }
            int range = ovector[1] - ovector[0];
            char* b = (char*) alloca(range+1);
            b[range] = '\0';
            char* a = data+ovector[0];
            char* substring = strncpy(b, a, range);
      char* tmp = (char*) malloc(range+1);
      tmp[range] = '\0';
      strncpy(tmp,substring,range);
      results[num]=tmp;
      num++;
            data = data+range+ovector[0];
        }
  return 0;
}

EXPORT bool rsplit(const char* regex, const char* str, char* a, char* b)
{ // TODO: harmonize with FFI
  int length = strlen(str);
  pcre *re;
  const char *error;
  int erroffset;
  // should probably move this regex compile to global
  re = pcre_compile(    regex, /* the regex */
                        0, /* default options */
                        &error, /* for error message */
                        &erroffset, /* for error offset */
                        NULL); /* use default character tables */
  int rc;
  int ovector[60];
  rc = pcre_exec(       re, /* result of pcre_compile() */
                        NULL, /* we didn’t study the regex */
                        str, /* the subject string */
                        strlen(str), /* the length of the subject string */
                        0, /* start at offset 0 in the subject */
                        0, /* default options */
                        ovector, /* vector of integers for substring information */
                        60); /* number of elements (NOT size in bytes) */

  if(rc<1 || rc>1) return false; // then we failed
  int range = ovector[0];
  int range2 = ovector[1];
  a[range] = '\0';;
  memcpy(a, str, range);
  b[length - range2] = '\0';
  memcpy(b, str + range2, length - range2);
  return true;
}

EXPORT char* rreplace(char* regex, char* str, char* replacement, char* result) {

  char* data = str; //string_value(pair_car(args));
        char* pattern = regex; //string_value(pair_cadr(args));
  char* replace = replacement;

        pcre *re;
        const char *error;
        int erroffset;
        re = pcre_compile(      pattern, /* the pattern */
                                0, /* default options */
                                &error, /* for error message */
                                &erroffset, /* for error offset */
                                NULL); /* use default character tables */

        int rc;
        int ovector[60];

        rc = pcre_exec( re, /* result of pcre_compile() */
                        NULL, /* we didn’t study the pattern */
                        data, /* the subject string */
                        strlen(data), /* the length of the subject string */
                        0, /* start at offset 0 in the subject */
                        0, /* default options */
                        ovector, /* vector of integers for substring information */
                        60); /* number of elements (NOT size in bytes) */

        // no match found return original string
        if(rc<1) {strcpy(result,str); return result;} // Return mk_string(_sc,data);
        // ok we have a match
        // first replace any groups in replace string (i.e. $1 $2 ...)
        char* res = (char*) "";
        char* sep = (char*) "$";
        char* tmp = 0;
  int datalength = strlen(data);
        int pos,range,size,cnt = 0;
  strcpy(result,replace);
        char* p = strtok(result,sep);
  if(p==NULL) { strcpy(result, str); return result; };
        do{
            char* cc;
            pos = strtol(p,&cc,10);
            range = (pos>0 && pos<20) ? ovector[(pos*2)+1] - ovector[pos*2] : 0;
      if(pos>=rc || range < 0 || range > datalength) {
        range = 0;
        cc = p;
      }
            size = strlen(res);
            tmp = (char*) alloca(size+range+strlen(cc)+1);
            tmp[size+range+strlen(cc)] = '\0';
            memcpy(tmp,res,size);
            memcpy(tmp+size,data+ovector[pos*2],range);
            memcpy(tmp+size+range,cc,strlen(cc));
            res = tmp;
            p = strtok(NULL, sep);
      cnt++;
        }while(p);
        // now we can use "rep" to replace the original regex match (i.e. ovector[0]-ovector[1])
        int lgth = ovector[0] + strlen(res) + strlen(data) - ovector[1] + 1;
        range = ovector[1] - ovector[0];
        if(lgth>4096) return str;
        result[lgth - 1] = '\0'; // TODO: lots of this can be simplified
        memcpy(result,data,ovector[0]);
        memcpy(result+ovector[0],res,strlen(res));
        memcpy(result+ovector[0]+strlen(res),data+ovector[1],strlen(data)-ovector[1]);
        return result;
}

EXPORT const char* sys_sharedir(){
  return extemp::UNIV::SHARE_DIR.c_str();
}

EXPORT char* sys_slurp_file(const char* fname)
{
    std::string filename(fname);
    std::string sharedir_filename(extemp::UNIV::SHARE_DIR + "/" + filename);

    // check raw path first, then prepend SHARE_DIR
    std::FILE *fp = std::fopen(filename.c_str(), "rb");
    if (!fp) {
      fp = std::fopen(sharedir_filename.c_str(), "rb");
    }

  if(fp){
    std::fseek(fp, 0, SEEK_END);
    size_t file_size = std::ftell(fp);
    char* buf = (char*)malloc(file_size*sizeof(char));
    std::rewind(fp);
    std::fread(buf, 1, file_size, fp);
    std::fclose(fp);

    buf[file_size-1] = '\0';
    return buf;
  }
  return NULL;
}

EXPORT int register_for_window_events()
{
#ifdef __APPLE__
  // to give Extempore it's own dock icon, etc
  return (int)[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
#else
  // implement the required "receive events" functionality for Linux
  // or Windows if necessary
  return 1;
#endif
}

namespace extemp
{

namespace UNIV
{

std::string SHARE_DIR = std::string(EXT_SHARE_DIR);
uint32_t NUM_FRAMES = 1024;
uint32_t CHANNELS = 2;
uint32_t IN_CHANNELS = 0;
uint32_t SAMPLE_RATE = 44100;
volatile uint64_t TIME = 0l;
uint64_t DEVICE_TIME = 0l;
double AUDIO_CLOCK_NOW = 0.0;
double AUDIO_CLOCK_BASE = 0.0;
uint64_t TIME_DIVISION = 1;
bool AUDIO_NONE = false;
uint32_t AUDIO_DEVICE = -1;
uint32_t AUDIO_IN_DEVICE = -1;
std::string AUDIO_DEVICE_NAME;
std::string AUDIO_IN_DEVICE_NAME;
double AUDIO_OUTPUT_LATENCY = 0.0;
double CLOCK_OFFSET = 0.0;
std::unordered_map<std::string, std::string> CMDPARAMS;
std::string ARCH;
std::string CPU;
std::vector<std::string> ATTRS;

// 0 is for ansi, 1 is for MSDos CMD shell
#ifdef _WIN32
uint32_t EXT_TERM = 1;
#else
uint32_t EXT_TERM = 0;
#endif
bool EXT_LOADBASE = true;

double midi2frq(double pitch)
{
    return 220.0 * pow(2.0,(pitch - 57.0)/12);
}

double frqRatio(double semitones)
{
    return pow(2.0, (semitones/12.0));
}

bool file_check(const std::string& filename)
{
    FILE* fd = fopen(filename.c_str(),"r");
    if(fd == NULL){
        return false;
    }else{
        fclose(fd);
        return true;
    }
}

struct dump_stack_frame {
    int op;
    pointer args;
    pointer envir;
    pointer code;
};

void printSchemeCell(scheme* _sc, std::stringstream& ss, pointer val, bool full, bool stringquotes)
{
    if(val == 0) {
        ss << "-ERROR BAD POINTER-";
        return;
    }
    if (pointer_type(val) > T_LAST_SYSTEM_TYPE) {
        printf("Bad cell type - not printing\n");
        return;
    }

    if(is_string(val)) {
        if(stringquotes) {
            ss << "\"" << string_value(val) << "\"";
        }else{
            ss << string_value(val);
        }
    }else if(is_symbol(val)){
        ss << symname(val);
    }else if(is_character(val)){
        ss << charvalue(val);
    }else if(is_environment(val)){
        ss << "#<ENVIRONMENT " << val << " ";
        if(full) {
            if(is_vector(val->_object._cons._car)) {
                ss << "<VECTOR-FRAME>";
            }else{
                printSchemeCell(_sc, ss, val->_object._cons._car, full, stringquotes);
            }
            ss << " ";
            printSchemeCell(_sc, ss, val->_object._cons._cdr, full, stringquotes);
        }
        ss << ">";
    }else if(is_proc(val)){
        ss << "#<PROC " << procname(val) << ">";
    }else if(is_foreign(val)){
        ss << "#<FOREIGN>";
    }else if(is_macro(val)){
        ss << "#<MACRO>";
    }else if(is_closure(val)){
        ss << "#<<CLOSURE " << val << ">";
        if(full) {
            ss << "<CODE ";
            printSchemeCell(_sc, ss, val->_object._cons._car, full, stringquotes);
            ss << "> ";
            printSchemeCell(_sc, ss, val->_object._cons._cdr, full, stringquotes);
            ss << ">>";
        }
    }else if(is_continuation(val)){
        ss << "#<<CONTINUATION " << val << ">";
        if(full) {
            unsigned int* stack = (unsigned int*) cptr_value(pair_cdr(val));
            int nframes = stack[0];
            dump_stack_frame* frames = (dump_stack_frame*)&stack[1];
            for(int j=0;j<nframes;j++)
            {
                ss << std::endl << std::endl << "FRAME(" << j << ")--------------------------";
                ss << std::endl << "OPCODE: " << frames[j].op; // << std::endl << "----------" << std::endl;

                // print args
                ss << std::endl << "ARGS: ";
                pointer args = frames[j].args;
                extemp::UNIV::printSchemeCell(_sc, ss, args, true, stringquotes);

                // copy code
                ss << std::endl << "CODE: ";
                pointer code = frames[j].code;
                extemp::UNIV::printSchemeCell(_sc, ss, code, true, stringquotes);

                ss << std::endl << "ENVIR: ";
                pointer envir = frames[j].envir;
                extemp::UNIV::printSchemeCell(_sc, ss, envir, true, stringquotes);
            }
        }
        ss << std::endl << ">>";
    }else if(is_cptr(val)){
        void* p = cptr_value(val);
        ss << "#<CPTR: " << p << ">";
    }else if(is_vector(val)){
        if(true) {
            ss << "#(";
            int i;
            long long num=val->_size;//  /2+ivalue_unchecked(val)%2;
            if(num > 1000 && !full) { // exit if larger than 1000 elements
                ss << " -- " << num << " elements -- )";
                return;
            }
            for(i=0; i<num; i++) {
                /* Vector cells will be treated like ordinary cells */
                printSchemeCell(_sc, ss, vector_elem(val,i), full, stringquotes);
                if(i+1 < num) ss << " ";
            }
            ss << ")";
        }
    }else if(is_port(val)){
        ss << "#<PORT" << val << ">";
    }else if(is_pair(val)){
        int lgth = list_length(_sc, val);
        if(lgth<0) // is pair
        {
            ss << "(";
            printSchemeCell(_sc, ss, val->_object._cons._car, full, stringquotes);
            ss << " . ";
            printSchemeCell(_sc, ss, val->_object._cons._cdr, full, stringquotes);
            ss << ")";
        }else if(lgth>1000 && !full) {
            ss << "( -- " << lgth << " elements -- )";
            return;
        }else{ // is list
            ss << "(";
            for(int i=0;i<lgth;i++)
            {
                printSchemeCell(_sc, ss, list_ref(_sc, i, val), full, stringquotes);
                if(i<(lgth-1)) ss << " ";
            }
            ss << ")";
        }
    }else if(is_foreign(val)){
        ss << "#<FOREIGN FUNC>";
    }else if(val == _sc->NIL){
        if(full) {
            ss << "()";
        }else{
            ss << "NIL";
        }
    }else if(_sc->T == val){
        ss << "#t";
    }else if(_sc->F == val){
        ss << "#f";
    }else if(is_integer(val)){
        ss << ivalue(val);
    }else if(is_rational(val)){
        ss << val->_object._number.value.ratvalue.n << "/" << val->_object._number.value.ratvalue.d;
    }else if(is_real(val)){
        if(full){
            ss << std::fixed << std::showpoint << std::setprecision(23) << rvalue(val);
        }else{
            ss << std::fixed << std::showpoint << /* << std::setprecision(15) <<*/ rvalue(val);
        }
    }else if(_sc->EOF_OBJ == val){
      ss << "#<EOF>";
    }else{
        ss << "UNKOWN VALUE: " << val << " (GC'd?) ";
    }

    return;
}

}

} //End Namespace


/*
 *
 * All rights reserved.
 *
 *
 *
 */

#include "UNIV.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <sstream>
#include <iosfwd>
#include <iomanip>
#include "pcre.h"
#include "SchemeFFI.h"
#include "SchemePrivate.h"

#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <AppKit/AppKit.h>
#else
#include <time.h>
#endif

#ifdef _WIN32
#include <malloc.h>
#include <Windows.h>

enum Windows_Color_Convert
{
    Black   = 0,
    Red     = FOREGROUND_RED,
    Green   = FOREGROUND_GREEN,
    Yellow  = FOREGROUND_RED   | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
    Blue    = FOREGROUND_BLUE  | FOREGROUND_INTENSITY,
    Magenta = FOREGROUND_RED   | FOREGROUND_BLUE,
    Cyan    = FOREGROUND_GREEN | FOREGROUND_BLUE,
    White   = FOREGROUND_RED   | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY
};

enum Windows_BGColor_convert
{
    BGBlack   = 0,
    BGRed     = BACKGROUND_RED,
    BGGreen   = BACKGROUND_GREEN,
    BGYellow  = BACKGROUND_RED   | BACKGROUND_GREEN | BACKGROUND_INTENSITY,
    BGBlue    = BACKGROUND_BLUE,
    BGMagenta = BACKGROUND_RED   | BACKGROUND_BLUE,
    BGCyan    = BACKGROUND_GREEN | BACKGROUND_BLUE,
    BGWhite   = BACKGROUND_RED   | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY,
};

int WINDOWS_COLORS[] = { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White };
int WINDOWS_BGCOLORS[] = { BGBlack, BGRed, BGGreen, BGYellow, BGBlue, BGMagenta, BGCyan, BGWhite };

#endif

static char base64_codesafe_encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                                                'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                                                'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                                                'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                                                'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                                                'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                                                'w', 'x', 'y', 'z', '0', '1', '2', '3',
                                                '4', '5', '6', '7', '8', '9', '_', '-'};

static char base64_std_encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                                           'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                                           'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                                           'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                                           'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                                           'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                                           'w', 'x', 'y', 'z', '0', '1', '2', '3',
                                           '4', '5', '6', '7', '8', '9', '+', '/'};

static char *base64_std_decoding_table = NULL;
static char *base64_codesafe_decoding_table = NULL;
static int _base64_mod_table[] = {0, 2, 1};

void base64_std_build_decoding_table() {

  base64_std_decoding_table = (char*) malloc(256);

    for (int i = 0; i < 64; i++)
        base64_std_decoding_table[(unsigned char) base64_std_encoding_table[i]] = i;
}

void base64_codesafe_build_decoding_table() {

  base64_codesafe_decoding_table = (char*) malloc(256);

    for (int i = 0; i < 64; i++)
        base64_codesafe_decoding_table[(unsigned char) base64_codesafe_encoding_table[i]] = i;
}

void base64_std_cleanup() {
    free(base64_std_decoding_table);
}

void base64_codesafe_cleanup() {
    free(base64_codesafe_decoding_table);
}

EXPORT char* cname_encode(char *data, size_t input_length, size_t *output_length)
{
    *output_length = 4 * ((input_length + 2) / 3);

    char *encoded_data = (char*) malloc(*output_length+1);
    encoded_data[*output_length] = 0;
    if (encoded_data == NULL) return NULL;

    for (unsigned i = 0, j = 0; i < input_length;) {

        uint32_t octet_a = i < input_length ? data[i++] : 0;
        uint32_t octet_b = i < input_length ? data[i++] : 0;
        uint32_t octet_c = i < input_length ? data[i++] : 0;

        uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

        encoded_data[j++] = base64_codesafe_encoding_table[(triple >> 3 * 6) & 0x3F];
        encoded_data[j++] = base64_codesafe_encoding_table[(triple >> 2 * 6) & 0x3F];
        encoded_data[j++] = base64_codesafe_encoding_table[(triple >> 1 * 6) & 0x3F];
        encoded_data[j++] = base64_codesafe_encoding_table[(triple >> 0 * 6) & 0x3F];
    }

    for (int i = 0; i < _base64_mod_table[input_length % 3]; i++) {
      encoded_data[*output_length - 1 - i] = 0; //'$';
    }

    return encoded_data;
}

EXPORT char* cname_decode(char *data, size_t input_length, size_t *output_length)
{
    if (base64_codesafe_decoding_table == NULL) base64_codesafe_build_decoding_table();

    char* d2 = NULL;
    // pad with $'s
    if (input_length % 4 != 0) {
      int lgthdiff = (4-(input_length % 4));
      char* d2 = (char*) malloc(input_length+lgthdiff);
      memcpy(d2,data,input_length);
      input_length = input_length+lgthdiff;
      for(int i=0;i<lgthdiff;i++) {
        d2[input_length-1-i] = '$';
      }
      data = d2;
    }

    if (input_length % 4 != 0) return NULL;
    *output_length = input_length / 4 * 3;
    if (data[input_length - 1] == '$') (*output_length)--;
    if (data[input_length - 2] == '$') (*output_length)--;

    char *decoded_data = (char*) malloc(*output_length+1);
    decoded_data[*output_length] = 0;
    if (decoded_data == NULL) return NULL;

    for (unsigned i = 0, j = 0; i < input_length;) {

        uint32_t sextet_a = data[i] == '$' ? 0 & i++ : base64_codesafe_decoding_table[unsigned(data[i++])];
        uint32_t sextet_b = data[i] == '$' ? 0 & i++ : base64_codesafe_decoding_table[unsigned(data[i++])];
        uint32_t sextet_c = data[i] == '$' ? 0 & i++ : base64_codesafe_decoding_table[unsigned(data[i++])];
        uint32_t sextet_d = data[i] == '$' ? 0 & i++ : base64_codesafe_decoding_table[unsigned(data[i++])];

        uint32_t triple = (sextet_a << 3 * 6)
        + (sextet_b << 2 * 6)
        + (sextet_c << 1 * 6)
        + (sextet_d << 0 * 6);

        if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
    }
    if (d2) free(d2);
    return decoded_data;
}

EXPORT char* base64_encode(const unsigned char *data, size_t input_length, size_t *output_length)
{
    *output_length = 4 * ((input_length + 2) / 3);

    char *encoded_data = (char*) malloc(*output_length+1);
    encoded_data[*output_length]=0;

    if (encoded_data == NULL) return NULL;

    for (unsigned i = 0, j = 0; i < input_length;) {

        uint32_t octet_a = i < input_length ? data[i++] : 0;
        uint32_t octet_b = i < input_length ? data[i++] : 0;
        uint32_t octet_c = i < input_length ? data[i++] : 0;

        uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

        encoded_data[j++] = base64_std_encoding_table[(triple >> 3 * 6) & 0x3F];
        encoded_data[j++] = base64_std_encoding_table[(triple >> 2 * 6) & 0x3F];
        encoded_data[j++] = base64_std_encoding_table[(triple >> 1 * 6) & 0x3F];
        encoded_data[j++] = base64_std_encoding_table[(triple >> 0 * 6) & 0x3F];
    }

    for (int i = 0; i < _base64_mod_table[input_length % 3]; i++)
        encoded_data[*output_length - 1 - i] = '=';

    return encoded_data;
}

EXPORT unsigned char* base64_decode(const char *data, size_t input_length, size_t *output_length)
{
    if (base64_std_decoding_table == NULL) base64_std_build_decoding_table();

    if (input_length % 4 != 0) return NULL;

    *output_length = input_length / 4 * 3;
    if (data[input_length - 1] == '=') (*output_length)--;
    if (data[input_length - 2] == '=') (*output_length)--;

    unsigned char *decoded_data = (unsigned char*) malloc(*output_length);
    if (decoded_data == NULL) return NULL;

    for (unsigned i = 0, j = 0; i < input_length;) {

        uint32_t sextet_a = data[i] == '=' ? 0 & i++ : base64_std_decoding_table[unsigned(data[i++])];
        uint32_t sextet_b = data[i] == '=' ? 0 & i++ : base64_std_decoding_table[unsigned(data[i++])];
        uint32_t sextet_c = data[i] == '=' ? 0 & i++ : base64_std_decoding_table[unsigned(data[i++])];
        uint32_t sextet_d = data[i] == '=' ? 0 & i++ : base64_std_decoding_table[unsigned(data[i++])];

        uint32_t triple = (sextet_a << 3 * 6)
        + (sextet_b << 2 * 6)
        + (sextet_c << 1 * 6)
        + (sextet_d << 0 * 6);

        if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
    }

    return decoded_data;
}

EXPORT bool rmatch(char* regex, const char* str)
{
  const char* data = str;
  char* pattern = regex;

  pcre *re;
  const char *error;
  int erroffset;

  re = pcre_compile(    pattern, /* the pattern */
                        0, /* default options */
                        &error, /* for error message */
                        &erroffset, /* for error offset */
                        NULL); /* use default character tables */

  int rc;
  int ovector[30];
  rc = pcre_exec(       re, /* result of pcre_compile() */
                        NULL, /* we didn’t study the pattern */
                        data, /* the subject string */
                        strlen(data), /* the length of the subject string */
                        0, /* start at offset 0 in the subject */
                        0, /* default options */
                        ovector, /* vector of integers for substring information */
                        30); /* number of elements (NOT size in bytes) */

  return (rc>=0) ? true : false;
}

//      rc = pcre_exec( re, /* result of pcre_compile() */
//                      NULL, /* we didn’t study the pattern */
//                      data, /* the subject string */
//                      strlen(data), /* the length of the subject string */
//                      0, /* start at offset 0 in the subject */
//                      60); /* number of elements (NOT size in bytes) */

//      // if failed to match return empty list

EXPORT int64_t rmatches(char* regex, char* str, char** results, int64_t maxnum)
    {
  char* data = str;
  char* pattern = regex;
        pcre *re;
        const char *error;
        int erroffset;
        re = pcre_compile(      pattern, /* the pattern */
                                0, /* default options */
                                &error, /* for error message */
                                &erroffset, /* for error offset */
                                NULL); /* use default character tables */

        // pointer to hold return results
        int rc;
        int ovector[60];
  int64_t num=0;

        while(true) {
            rc = pcre_exec(     re, /* result of pcre_compile() */
                                NULL, /* we didn’t study the pattern */
                                data, /* the subject string */
                                strlen(data), /* the length of the subject string */
                                0, /* start at offset 0 in the subject */
                                0, /* default options */
                                ovector, /* vector of integers for substring information */
                                60); /* number of elements (NOT size in bytes) */

            if(rc<1 || num>=maxnum) {
        return num;
            }
            int range = ovector[1] - ovector[0];
            char* b = (char*) alloca(range+1);
            b[range] = '\0';
            char* a = data+ovector[0];
            char* substring = strncpy(b, a, range);
      char* tmp = (char*) malloc(range+1);
      tmp[range] = '\0';
      strncpy(tmp,substring,range);
      results[num]=tmp;
      num++;
            data = data+range+ovector[0];
        }
  return 0;
}

EXPORT bool rsplit(const char* regex, const char* str, char* a, char* b)
{ // TODO: harmonize with FFI
  int length = strlen(str);
  pcre *re;
  const char *error;
  int erroffset;
  // should probably move this regex compile to global
  re = pcre_compile(    regex, /* the regex */
                        0, /* default options */
                        &error, /* for error message */
                        &erroffset, /* for error offset */
                        NULL); /* use default character tables */
  int rc;
  int ovector[60];
  rc = pcre_exec(       re, /* result of pcre_compile() */
                        NULL, /* we didn’t study the regex */
                        str, /* the subject string */
                        strlen(str), /* the length of the subject string */
                        0, /* start at offset 0 in the subject */
                        0, /* default options */
                        ovector, /* vector of integers for substring information */
                        60); /* number of elements (NOT size in bytes) */

  if(rc<1 || rc>1) return false; // then we failed
  int range = ovector[0];
  int range2 = ovector[1];
  a[range] = '\0';;
  memcpy(a, str, range);
  b[length - range2] = '\0';
  memcpy(b, str + range2, length - range2);
  return true;
}

EXPORT char* rreplace(char* regex, char* str, char* replacement, char* result) {

 //string_value(pair_car(args));
        char* pattern = regex; //string_value(pair_cadr(args));
  char* replace = replacement;

        pcre *re;
        const char *error;
        int erroffset;
        re = pcre_compile(      pattern, /* the pattern */
                                0, /* default options */
                                &error, /* for error message */
                                &erroffset, /* for error offset */
                                NULL); /* use default character tables */

        int rc;
        int ovector[60];

        rc = pcre_exec( re, /* result of pcre_compile() */
                        NULL, /* we didn’t study the pattern */
                        data, /* the subject string */
                        strlen(data), /* the length of the subject string */
                        0, /* start at offset 0 in the subject */
                        0, /* default options */
                        ovector, /* vector of integers for substring information */
                        60); /* number of elements (NOT size in bytes) */

        // no match found return original string
        if(rc<1) {strcpy(result,str); return result;} // Return mk_string(_sc,data);
        // ok we have a match
        // first replace any groups in replace string (i.e. $1 $2 ...)
        char* res = (char*) "";
        char* sep = (char*) "$";
        char* tmp = 0;
  int datalength = strlen(data);
        int pos,range,size,cnt = 0;
  strcpy(result,replace);
        char* p = strtok(result,sep);
  if(p==NULL) { strcpy(result, str); return result; };
        do{
            char* cc;
            pos = strtol(p,&cc,10);
            range = (pos>0 && pos<20) ? ovector[(pos*2)+1] - ovector[pos*2] : 0;
      if(pos>=rc || range < 0 || range > datalength) {
        range = 0;
        cc = p;
      }
            size = strlen(res);
            tmp = (char*) alloca(size+range+strlen(cc)+1);
            tmp[size+range+strlen(cc)] = '\0';
            memcpy(tmp,res,size);
            memcpy(tmp+size,data+ovector[pos*2],range);
            memcpy(tmp+size+range,cc,strlen(cc));
            res = tmp;
            p = strtok(NULL, sep);
      cnt++;
        }while(p);
        // now we can use "rep" to replace the original regex match (i.e. ovector[0]-ovector[1])
        int lgth = ovector[0] + strlen(res) + strlen(data) - ovector[1] + 1;
        range = ovector[1] - ovector[0];
        if(lgth>4096) return str;
        result[lgth - 1] = '\0'; // TODO: lots of this can be simplified
        memcpy(result,data,ovector[0]);
        memcpy(result+ovector[0],res,strlen(res));
        memcpy(result+ovector[0]+strlen(res),data+ovector[1],strlen(data)-ovector[1]);
        return result;
}

EXPORT const char* sys_sharedir(){
  return extemp::UNIV::SHARE_DIR.c_str();
}

EXPORT char* sys_slurp_file(const char* fname)
{
    std::string filename(fname);
    std::string sharedir_filename(extemp::UNIV::SHARE_DIR + "/" + filename);

    // check raw path first, then prepend SHARE_DIR
    std::FILE *fp = std::fopen(filename.c_str(), "rb");
    if (!fp) {
      fp = std::fopen(sharedir_filename.c_str(), "rb");
    }

  if(fp){
    std::fseek(fp, 0, SEEK_END);
    size_t file_size = std::ftell(fp);
    char* buf = (char*)malloc(file_size*sizeof(char));
    std::rewind(fp);
    std::fread(buf, 1, file_size, fp);
    std::fclose(fp);

    buf[file_size-1] = '\0';
    return buf;
  }
  return NULL;
}

EXPORT int register_for_window_events()
{
#ifdef __APPLE__
  // to give Extempore it's own dock icon, etc
  return (int)[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
#else
  // implement the required "receive events" functionality for Linux
  // or Windows if necessary
  return 1;
#endif
}

namespace extemp
{

namespace UNIV
{

std::string SHARE_DIR = std::string(EXT_SHARE_DIR);
uint32_t NUM_FRAMES = 1024;
uint32_t CHANNELS = 2;
uint32_t IN_CHANNELS = 0;
uint32_t SAMPLE_RATE = 44100;
volatile uint64_t TIME = 0l;
uint64_t DEVICE_TIME = 0l;
double AUDIO_CLOCK_NOW = 0.0;
double AUDIO_CLOCK_BASE = 0.0;
uint64_t TIME_DIVISION = 1;
bool AUDIO_NONE = false;
uint32_t AUDIO_DEVICE = -1;
uint32_t AUDIO_IN_DEVICE = -1;
std::string AUDIO_DEVICE_NAME;
std::string AUDIO_IN_DEVICE_NAME;
double AUDIO_OUTPUT_LATENCY = 0.0;
double CLOCK_OFFSET = 0.0;
std::unordered_map<std::string, std::string> CMDPARAMS;
std::string ARCH;
std::string CPU;
std::vector<std::string> ATTRS;

// 0 is for ansi, 1 is for MSDos CMD shell
#ifdef _WIN32
uint32_t EXT_TERM = 1;
#else
uint32_t EXT_TERM = 0;
#endif
bool EXT_LOADBASE = true;

double midi2frq(double pitch)
{
    return 220.0 * pow(2.0,(pitch - 57.0)/12);
}

double frqRatio(double semitones)
{
    return pow(2.0, (semitones/12.0));
}

bool file_check(const std::string& filename)
{
    FILE* fd = fopen(filename.c_str(),"r");
    if(fd == NULL){
        return false;
    }else{
        fclose(fd);
        return true;
    }
}

struct dump_stack_frame {
    int op;
    pointer args;
    pointer envir;
    pointer code;
};

void printSchemeCell(scheme* _sc, std::stringstream& ss, pointer val, bool full, bool stringquotes)
{
    if(val == 0) {
        ss << "-ERROR BAD POINTER-";
        return;
    }
    if (pointer_type(val) > T_LAST_SYSTEM_TYPE) {
        printf("Bad cell type - not printing\n");
        return;
    }

    if(is_string(val)) {
        if(stringquotes) {
            ss << "\"" << string_value(val) << "\"";
        }else{
            ss << string_value(val);
        }
    }else if(is_symbol(val)){
        ss << symname(val);
    }else if(is_character(val)){
        ss << charvalue(val);
    }else if(is_environment(val)){
        ss << "#<ENVIRONMENT " << val << " ";
        if(full) {
            if(is_vector(val->_object._cons._car)) {
                ss << "<VECTOR-FRAME>";
            }else{
                printSchemeCell(_sc, ss, val->_object._cons._car, full, stringquotes);
            }
            ss << " ";
            printSchemeCell(_sc, ss, val->_object._cons._cdr, full, stringquotes);
        }
        ss << ">";
    }else if(is_proc(val)){
        ss << "#<PROC " << procname(val) << ">";
    }else if(is_foreign(val)){
        ss << "#<FOREIGN>";
    }else if(is_macro(val)){
        ss << "#<MACRO>";
    }else if(is_closure(val)){
        ss << "#<<CLOSURE " << val << ">";
        if(full) {
            ss << "<CODE ";
            printSchemeCell(_sc, ss, val->_object._cons._car, full, stringquotes);
            ss << "> ";
            printSchemeCell(_sc, ss, val->_object._cons._cdr, full, stringquotes);
            ss << ">>";
        }
    }else if(is_continuation(val)){
        ss << "#<<CONTINUATION " << val << ">";
        if(full) {
            unsigned int* stack = (unsigned int*) cptr_value(pair_cdr(val));
            int nframes = stack[0];
            dump_stack_frame* frames = (dump_stack_frame*)&stack[1];
            for(int j=0;j<nframes;j++)
            {
                ss << std::endl << std::endl << "FRAME(" << j << ")--------------------------";
                ss << std::endl << "OPCODE: " << frames[j].op; // << std::endl << "----------" << std::endl;

                // print args
                ss << std::endl << "ARGS: ";
                pointer args = frames[j].args;
                extemp::UNIV::printSchemeCell(_sc, ss, args, true, stringquotes);

                // copy code
                ss << std::endl << "CODE: ";
                pointer code = frames[j].code;
                extemp::UNIV::printSchemeCell(_sc, ss, code, true, stringquotes);

                ss << std::endl << "ENVIR: ";
                pointer envir = frames[j].envir;
                extemp::UNIV::printSchemeCell(_sc, ss, envir, true, stringquotes);
            }
        }
        ss << std::endl << ">>";
    }else if(is_cptr(val)){
        void* p = cptr_value(val);
        ss << "#<CPTR: " << p << ">";
    }else if(is_vector(val)){
        if(true) {
            ss << "#(";
            int i;
            long long num=val->_size;//  /2+ivalue_unchecked(val)%2;
            if(num > 1000 && !full) { // exit if larger than 1000 elements
                ss << " -- " << num << " elements -- )";
                return;
            }
            for(i=0; i<num; i++) {
                /* Vector cells will be treated like ordinary cells */
                printSchemeCell(_sc, ss, vector_elem(val,i), full, stringquotes);
                if(i+1 < num) ss << " ";
            }
            ss << ")";
        }
    }else if(is_port(val)){
        ss << "#<PORT" << val << ">";
    }else if(is_pair(val)){
        int lgth = list_length(_sc, val);
        if(lgth<0) // is pair
        {
            ss << "(";
            printSchemeCell(_sc, ss, val->_object._cons._car, full, stringquotes);
            ss << " . ";
            printSchemeCell(_sc, ss, val->_object._cons._cdr, full, stringquotes);
            ss << ")";
        }else if(lgth>1000 && !full) {
            ss << "( -- " << lgth << " elements -- )";
            return;
        }else{ // is list
            ss << "(";
            for(int i=0;i<lgth;i++)
            {
                printSchemeCell(_sc, ss, list_ref(_sc, i, val), full, stringquotes);
                if(i<(lgth-1)) ss << " ";
            }
            ss << ")";
        }
    }else if(is_foreign(val)){
        ss << "#<FOREIGN FUNC>";
    }else if(val == _sc->NIL){
        if(full) {
            ss << "()";
        }else{
            ss << "NIL";
        }
    }else if(_sc->T == val){
        ss << "#t";
    }else if(_sc->F == val){
        ss << "#f";
    }else if(is_integer(val)){
        ss << ivalue(val);
    }else if(is_rational(val)){
        ss << val->_object._number.value.ratvalue.n << "/" << val->_object._number.value.ratvalue.d;
    }else if(is_real(val)){
        if(full){
            ss << std::fixed << std::showpoint << std::setprecision(23) << rvalue(val);
        }else{
            ss << std::fixed << std::showpoint << /* << std::setprecision(15) <<*/ rvalue(val);
        }
    }else if(_sc->EOF_OBJ == val){
      ss << "#<EOF>";
    }else{
        ss << "UNKOWN VALUE: " << val << " (GC'd?) ";
    }

    return;
}

}

} //End Namespace


for(int i=0;i<lgthdiff;i++) {
        d2[input_length-1-i] = '$';
      }

/*
 *
 * All rights reserved.
 *
 *
 *
 */

#include "UNIV.h"
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <sstream>
#include <iosfwd>
#include <iomanip>
#include "pcre.h"
#include "SchemeFFI.h"
#include "SchemePrivate.h"

#ifdef __APPLE__
#include <CoreFoundation/CoreFoundation.h>
#include <AppKit/AppKit.h>
#else
#include <time.h>
#endif

#ifdef _WIN32
#include <malloc.h>
#include <Windows.h>

enum Windows_Color_Convert
{
    Black   = 0,
    Red     = FOREGROUND_RED,
    Green   = FOREGROUND_GREEN,
    Yellow  = FOREGROUND_RED   | FOREGROUND_GREEN | FOREGROUND_INTENSITY,
    Blue    = FOREGROUND_BLUE  | FOREGROUND_INTENSITY,
    Magenta = FOREGROUND_RED   | FOREGROUND_BLUE,
    Cyan    = FOREGROUND_GREEN | FOREGROUND_BLUE,
    White   = FOREGROUND_RED   | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY
};

enum Windows_BGColor_convert
{
    BGBlack   = 0,
    BGRed     = BACKGROUND_RED,
    BGGreen   = BACKGROUND_GREEN,
    BGYellow  = BACKGROUND_RED   | BACKGROUND_GREEN | BACKGROUND_INTENSITY,
    BGBlue    = BACKGROUND_BLUE,
    BGMagenta = BACKGROUND_RED   | BACKGROUND_BLUE,
    BGCyan    = BACKGROUND_GREEN | BACKGROUND_BLUE,
    BGWhite   = BACKGROUND_RED   | BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY,
};

int WINDOWS_COLORS[] = { Black, Red, Green, Yellow, Blue, Magenta, Cyan, White };
int WINDOWS_BGCOLORS[] = { BGBlack, BGRed, BGGreen, BGYellow, BGBlue, BGMagenta, BGCyan, BGWhite };

#endif

static char base64_codesafe_encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                                                'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                                                'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                                                'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                                                'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                                                'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                                                'w', 'x', 'y', 'z', '0', '1', '2', '3',
                                                '4', '5', '6', '7', '8', '9', '_', '-'};

static char base64_std_encoding_table[] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
                                           'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
                                           'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
                                           'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
                                           'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
                                           'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
                                           'w', 'x', 'y', 'z', '0', '1', '2', '3',
                                           '4', '5', '6', '7', '8', '9', '+', '/'};

static char *base64_std_decoding_table = NULL;
static char *base64_codesafe_decoding_table = NULL;
static int _base64_mod_table[] = {0, 2, 1};

void base64_std_build_decoding_table() {

  base64_std_decoding_table = (char*) malloc(256);

    for (int i = 0; i < 64; i++)
        base64_std_decoding_table[(unsigned char) base64_std_encoding_table[i]] = i;
}

void base64_codesafe_build_decoding_table() {

  base64_codesafe_decoding_table = (char*) malloc(256);

    for (int i = 0; i < 64; i++)
        base64_codesafe_decoding_table[(unsigned char) base64_codesafe_encoding_table[i]] = i;
}

void base64_std_cleanup() {
    free(base64_std_decoding_table);
}

void base64_codesafe_cleanup() {
    free(base64_codesafe_decoding_table);
}

EXPORT char* cname_encode(char *data, size_t input_length, size_t *output_length)
{
    *output_length = 4 * ((input_length + 2) / 3);

    char *encoded_data = (char*) malloc(*output_length+1);
    encoded_data[*output_length] = 0;
    if (encoded_data == NULL) return NULL;

    for (unsigned i = 0, j = 0; i < input_length;) {

        uint32_t octet_a = i < input_length ? data[i++] : 0;
        uint32_t octet_b = i < input_length ? data[i++] : 0;
        uint32_t octet_c = i < input_length ? data[i++] : 0;

        uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

        encoded_data[j++] = base64_codesafe_encoding_table[(triple >> 3 * 6) & 0x3F];
        encoded_data[j++] = base64_codesafe_encoding_table[(triple >> 2 * 6) & 0x3F];
        encoded_data[j++] = base64_codesafe_encoding_table[(triple >> 1 * 6) & 0x3F];
        encoded_data[j++] = base64_codesafe_encoding_table[(triple >> 0 * 6) & 0x3F];
    }

    for (int i = 0; i < _base64_mod_table[input_length % 3]; i++) {
      encoded_data[*output_length - 1 - i] = 0; //'$';
    }

    return encoded_data;
}

EXPORT char* cname_decode(char *data, size_t input_length, size_t *output_length)
{
    if (base64_codesafe_decoding_table == NULL) base64_codesafe_build_decoding_table();

    char* d2 = NULL;
    // pad with $'s
    if (input_length % 4 != 0) {
      int lgthdiff = (4-(input_length % 4));
      char* d2 = (char*) malloc(input_length+lgthdiff);
      memcpy(d2,data,input_length);
      input_length = input_length+lgthdiff;

      data = d2;
    }

    if (input_length % 4 != 0) return NULL;
    *output_length = input_length / 4 * 3;
    if (data[input_length - 1] == '$') (*output_length)--;
    if (data[input_length - 2] == '$') (*output_length)--;

    char *decoded_data = (char*) malloc(*output_length+1);
    decoded_data[*output_length] = 0;
    if (decoded_data == NULL) return NULL;

    for (unsigned i = 0, j = 0; i < input_length;) {

        uint32_t sextet_a = data[i] == '$' ? 0 & i++ : base64_codesafe_decoding_table[unsigned(data[i++])];
        uint32_t sextet_b = data[i] == '$' ? 0 & i++ : base64_codesafe_decoding_table[unsigned(data[i++])];
        uint32_t sextet_c = data[i] == '$' ? 0 & i++ : base64_codesafe_decoding_table[unsigned(data[i++])];
        uint32_t sextet_d = data[i] == '$' ? 0 & i++ : base64_codesafe_decoding_table[unsigned(data[i++])];

        uint32_t triple = (sextet_a << 3 * 6)
        + (sextet_b << 2 * 6)
        + (sextet_c << 1 * 6)
        + (sextet_d << 0 * 6);

        if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
    }
    if (d2) free(d2);
    return decoded_data;
}

EXPORT char* base64_encode(const unsigned char *data, size_t input_length, size_t *output_length)
{
    *output_length = 4 * ((input_length + 2) / 3);

    char *encoded_data = (char*) malloc(*output_length+1);
    encoded_data[*output_length]=0;

    if (encoded_data == NULL) return NULL;

    for (unsigned i = 0, j = 0; i < input_length;) {

        uint32_t octet_a = i < input_length ? data[i++] : 0;
        uint32_t octet_b = i < input_length ? data[i++] : 0;
        uint32_t octet_c = i < input_length ? data[i++] : 0;

        uint32_t triple = (octet_a << 0x10) + (octet_b << 0x08) + octet_c;

        encoded_data[j++] = base64_std_encoding_table[(triple >> 3 * 6) & 0x3F];
        encoded_data[j++] = base64_std_encoding_table[(triple >> 2 * 6) & 0x3F];
        encoded_data[j++] = base64_std_encoding_table[(triple >> 1 * 6) & 0x3F];
        encoded_data[j++] = base64_std_encoding_table[(triple >> 0 * 6) & 0x3F];
    }

    for (int i = 0; i < _base64_mod_table[input_length % 3]; i++)
        encoded_data[*output_length - 1 - i] = '=';

    return encoded_data;
}

EXPORT unsigned char* base64_decode(const char *data, size_t input_length, size_t *output_length)
{
    if (base64_std_decoding_table == NULL) base64_std_build_decoding_table();

    if (input_length % 4 != 0) return NULL;

    *output_length = input_length / 4 * 3;
    if (data[input_length - 1] == '=') (*output_length)--;
    if (data[input_length - 2] == '=') (*output_length)--;

    unsigned char *decoded_data = (unsigned char*) malloc(*output_length);
    if (decoded_data == NULL) return NULL;

    for (unsigned i = 0, j = 0; i < input_length;) {

        uint32_t sextet_a = data[i] == '=' ? 0 & i++ : base64_std_decoding_table[unsigned(data[i++])];
        uint32_t sextet_b = data[i] == '=' ? 0 & i++ : base64_std_decoding_table[unsigned(data[i++])];
        uint32_t sextet_c = data[i] == '=' ? 0 & i++ : base64_std_decoding_table[unsigned(data[i++])];
        uint32_t sextet_d = data[i] == '=' ? 0 & i++ : base64_std_decoding_table[unsigned(data[i++])];

        uint32_t triple = (sextet_a << 3 * 6)
        + (sextet_b << 2 * 6)
        + (sextet_c << 1 * 6)
        + (sextet_d << 0 * 6);

        if (j < *output_length) decoded_data[j++] = (triple >> 2 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 1 * 8) & 0xFF;
        if (j < *output_length) decoded_data[j++] = (triple >> 0 * 8) & 0xFF;
    }

    return decoded_data;
}

EXPORT bool rmatch(char* regex, const char* str)
{
  const char* data = str;
  char* pattern = regex;

  pcre *re;
  const char *error;
  int erroffset;

  re = pcre_compile(    pattern, /* the pattern */
                        0, /* default options */
                        &error, /* for error message */
                        &erroffset, /* for error offset */
                        NULL); /* use default character tables */

  int rc;
  int ovector[30];
  rc = pcre_exec(       re, /* result of pcre_compile() */
                        NULL, /* we didn’t study the pattern */
                        data, /* the subject string */
                        strlen(data), /* the length of the subject string */
                        0, /* start at offset 0 in the subject */
                        0, /* default options */
                        ovector, /* vector of integers for substring information */
                        30); /* number of elements (NOT size in bytes) */

  return (rc>=0) ? true : false;
}

//      rc = pcre_exec( re, /* result of pcre_compile() */
//                      NULL, /* we didn’t study the pattern */
//                      data, /* the subject string */
//                      strlen(data), /* the length of the subject string */
//                      0, /* start at offset 0 in the subject */
//                      60); /* number of elements (NOT size in bytes) */

//      // if failed to match return empty list

EXPORT int64_t rmatches(char* regex, char* str, char** results, int64_t maxnum)
    {
  char* data = str;
  char* pattern = regex;
        pcre *re;
        const char *error;
        int erroffset;
        re = pcre_compile(      pattern, /* the pattern */
                                0, /* default options */
                                &error, /* for error message */
                                &erroffset, /* for error offset */
                                NULL); /* use default character tables */

        // pointer to hold return results
        int rc;
        int ovector[60];
  int64_t num=0;

        while(true) {
            rc = pcre_exec(     re, /* result of pcre_compile() */
                                NULL, /* we didn’t study the pattern */
                                data, /* the subject string */
                                strlen(data), /* the length of the subject string */
                                0, /* start at offset 0 in the subject */
                                0, /* default options */
                                ovector, /* vector of integers for substring information */
                                60); /* number of elements (NOT size in bytes) */

            if(rc<1 || num>=maxnum) {
        return num;
            }
            int range = ovector[1] - ovector[0];
            char* b = (char*) alloca(range+1);
            b[range] = '\0';
            char* a = data+ovector[0];
            char* substring = strncpy(b, a, range);
      char* tmp = (char*) malloc(range+1);
      tmp[range] = '\0';
      strncpy(tmp,substring,range);
      results[num]=tmp;
      num++;
            data = data+range+ovector[0];
        }
  return 0;
}

EXPORT bool rsplit(const char* regex, const char* str, char* a, char* b)
{ // TODO: harmonize with FFI
  int length = strlen(str);
  pcre *re;
  const char *error;
  int erroffset;
  // should probably move this regex compile to global
  re = pcre_compile(    regex, /* the regex */
                        0, /* default options */
                        &error, /* for error message */
                        &erroffset, /* for error offset */
                        NULL); /* use default character tables */
  int rc;
  int ovector[60];
  rc = pcre_exec(       re, /* result of pcre_compile() */
                        NULL, /* we didn’t study the regex */
                        str, /* the subject string */
                        strlen(str), /* the length of the subject string */
                        0, /* start at offset 0 in the subject */
                        0, /* default options */
                        ovector, /* vector of integers for substring information */
                        60); /* number of elements (NOT size in bytes) */

  if(rc<1 || rc>1) return false; // then we failed
  int range = ovector[0];
  int range2 = ovector[1];
  a[range] = '\0';;
  memcpy(a, str, range);
  b[length - range2] = '\0';
  memcpy(b, str + range2, length - range2);
  return true;
}

EXPORT char* rreplace(char* regex, char* str, char* replacement, char* result) {

  char* data = str; //string_value(pair_car(args));
        char* pattern = regex; //string_value(pair_cadr(args));
  char* replace = replacement;

        pcre *re;
        const char *error;
        int erroffset;
        re = pcre_compile(      pattern, /* the pattern */
                                0, /* default options */
                                &error, /* for error message */
                                &erroffset, /* for error offset */
                                NULL); /* use default character tables */

        int rc;
        int ovector[60];

        rc = pcre_exec( re, /* result of pcre_compile() */
                        NULL, /* we didn’t study the pattern */
                        data, /* the subject string */
                        strlen(data), /* the length of the subject string */
                        0, /* start at offset 0 in the subject */
                        0, /* default options */
                        ovector, /* vector of integers for substring information */
                        60); /* number of elements (NOT size in bytes) */

        // no match found return original string
        if(rc<1) {strcpy(result,str); return result;} // Return mk_string(_sc,data);
        // ok we have a match
        // first replace any groups in replace string (i.e. $1 $2 ...)
        char* res = (char*) "";
        char* sep = (char*) "$";
        char* tmp = 0;
  int datalength = strlen(data);
        int pos,range,size,cnt = 0;
  strcpy(result,replace);
        char* p = strtok(result,sep);
  if(p==NULL) { strcpy(result, str); return result; };
        do{
            char* cc;
            pos = strtol(p,&cc,10);
            range = (pos>0 && pos<20) ? ovector[(pos*2)+1] - ovector[pos*2] : 0;
      if(pos>=rc || range < 0 || range > datalength) {
        range = 0;
        cc = p;
      }
            size = strlen(res);
            tmp = (char*) alloca(size+range+strlen(cc)+1);
            tmp[size+range+strlen(cc)] = '\0';
            memcpy(tmp,res,size);
            memcpy(tmp+size,data+ovector[pos*2],range);
            memcpy(tmp+size+range,cc,strlen(cc));
            res = tmp;
            p = strtok(NULL, sep);
      cnt++;
        }while(p);
        // now we can use "rep" to replace the original regex match (i.e. ovector[0]-ovector[1])
        int lgth = ovector[0] + strlen(res) + strlen(data) - ovector[1] + 1;
        range = ovector[1] - ovector[0];
        if(lgth>4096) return str;
        result[lgth - 1] = '\0'; // TODO: lots of this can be simplified
        memcpy(result,data,ovector[0]);
        memcpy(result+ovector[0],res,strlen(res));
        memcpy(result+ovector[0]+strlen(res),data+ovector[1],strlen(data)-ovector[1]);
        return result;
}

EXPORT const char* sys_sharedir(){
  return extemp::UNIV::SHARE_DIR.c_str();
}

EXPORT char* sys_slurp_file(const char* fname)
{
    std::string filename(fname);
    std::string sharedir_filename(extemp::UNIV::SHARE_DIR + "/" + filename);

    // check raw path first, then prepend SHARE_DIR
    std::FILE *fp = std::fopen(filename.c_str(), "rb");
    if (!fp) {
      fp = std::fopen(sharedir_filename.c_str(), "rb");
    }

  if(fp){
    std::fseek(fp, 0, SEEK_END);
    size_t file_size = std::ftell(fp);
    char* buf = (char*)malloc(file_size*sizeof(char));
    std::rewind(fp);
    std::fread(buf, 1, file_size, fp);
    std::fclose(fp);

    buf[file_size-1] = '\0';
    return buf;
  }
  return NULL;
}

EXPORT int register_for_window_events()
{
#ifdef __APPLE__
  // to give Extempore it's own dock icon, etc
  return (int)[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
#else
  // implement the required "receive events" functionality for Linux
  // or Windows if necessary
  return 1;
#endif
}

namespace extemp
{

namespace UNIV
{

std::string SHARE_DIR = std::string(EXT_SHARE_DIR);
uint32_t NUM_FRAMES = 1024;
uint32_t CHANNELS = 2;
uint32_t IN_CHANNELS = 0;
uint32_t SAMPLE_RATE = 44100;
volatile uint64_t TIME = 0l;
uint64_t DEVICE_TIME = 0l;
double AUDIO_CLOCK_NOW = 0.0;
double AUDIO_CLOCK_BASE = 0.0;
uint64_t TIME_DIVISION = 1;
bool AUDIO_NONE = false;
uint32_t AUDIO_DEVICE = -1;
uint32_t AUDIO_IN_DEVICE = -1;
std::string AUDIO_DEVICE_NAME;
std::string AUDIO_IN_DEVICE_NAME;
double AUDIO_OUTPUT_LATENCY = 0.0;
double CLOCK_OFFSET = 0.0;
std::unordered_map<std::string, std::string> CMDPARAMS;
std::string ARCH;
std::string CPU;
std::vector<std::string> ATTRS;

// 0 is for ansi, 1 is for MSDos CMD shell
#ifdef _WIN32
uint32_t EXT_TERM = 1;
#else
uint32_t EXT_TERM = 0;
#endif
bool EXT_LOADBASE = true;

double midi2frq(double pitch)
{
    return 220.0 * pow(2.0,(pitch - 57.0)/12);
}

double frqRatio(double semitones)
{
    return pow(2.0, (semitones/12.0));
}

bool file_check(const std::string& filename)
{
    FILE* fd = fopen(filename.c_str(),"r");
    if(fd == NULL){
        return false;
    }else{
        fclose(fd);
        return true;
    }
}

struct dump_stack_frame {
    int op;
    pointer args;
    pointer envir;
    pointer code;
};

void printSchemeCell(scheme* _sc, std::stringstream& ss, pointer val, bool full, bool stringquotes)
{
    if(val == 0) {
        ss << "-ERROR BAD POINTER-";
        return;
    }
    if (pointer_type(val) > T_LAST_SYSTEM_TYPE) {
        printf("Bad cell type - not printing\n");
        return;
    }

    if(is_string(val)) {
        if(stringquotes) {
            ss << "\"" << string_value(val) << "\"";
        }else{
            ss << string_value(val);
        }
    }else if(is_symbol(val)){
        ss << symname(val);
    }else if(is_character(val)){
        ss << charvalue(val);
    }else if(is_environment(val)){
        ss << "#<ENVIRONMENT " << val << " ";
        if(full) {
            if(is_vector(val->_object._cons._car)) {
                ss << "<VECTOR-FRAME>";
            }else{
                printSchemeCell(_sc, ss, val->_object._cons._car, full, stringquotes);
            }
            ss << " ";
            printSchemeCell(_sc, ss, val->_object._cons._cdr, full, stringquotes);
        }
        ss << ">";
    }else if(is_proc(val)){
        ss << "#<PROC " << procname(val) << ">";
    }else if(is_foreign(val)){
        ss << "#<FOREIGN>";
    }else if(is_macro(val)){
        ss << "#<MACRO>";
    }else if(is_closure(val)){
        ss << "#<<CLOSURE " << val << ">";
        if(full) {
            ss << "<CODE ";
            printSchemeCell(_sc, ss, val->_object._cons._car, full, stringquotes);
            ss << "> ";
            printSchemeCell(_sc, ss, val->_object._cons._cdr, full, stringquotes);
            ss << ">>";
        }
    }else if(is_continuation(val)){
        ss << "#<<CONTINUATION " << val << ">";
        if(full) {
            unsigned int* stack = (unsigned int*) cptr_value(pair_cdr(val));
            int nframes = stack[0];
            dump_stack_frame* frames = (dump_stack_frame*)&stack[1];
            for(int j=0;j<nframes;j++)
            {
                ss << std::endl << std::endl << "FRAME(" << j << ")--------------------------";
                ss << std::endl << "OPCODE: " << frames[j].op; // << std::endl << "----------" << std::endl;

                // print args
                ss << std::endl << "ARGS: ";
                pointer args = frames[j].args;
                extemp::UNIV::printSchemeCell(_sc, ss, args, true, stringquotes);

                // copy code
                ss << std::endl << "CODE: ";
                pointer code = frames[j].code;
                extemp::UNIV::printSchemeCell(_sc, ss, code, true, stringquotes);

                ss << std::endl << "ENVIR: ";
                pointer envir = frames[j].envir;
                extemp::UNIV::printSchemeCell(_sc, ss, envir, true, stringquotes);
            }
        }
        ss << std::endl << ">>";
    }else if(is_cptr(val)){
        void* p = cptr_value(val);
        ss << "#<CPTR: " << p << ">";
    }else if(is_vector(val)){
        if(true) {
            ss << "#(";
            int i;
            long long num=val->_size;//  /2+ivalue_unchecked(val)%2;
            if(num > 1000 && !full) { // exit if larger than 1000 elements
                ss << " -- " << num << " elements -- )";
                return;
            }
            for(i=0; i<num; i++) {
                /* Vector cells will be treated like ordinary cells */
                printSchemeCell(_sc, ss, vector_elem(val,i), full, stringquotes);
                if(i+1 < num) ss << " ";
            }
            ss << ")";
        }
    }else if(is_port(val)){
        ss << "#<PORT" << val << ">";
    }else if(is_pair(val)){
        int lgth = list_length(_sc, val);
        if(lgth<0) // is pair
        {
            ss << "(";
            printSchemeCell(_sc, ss, val->_object._cons._car, full, stringquotes);
            ss << " . ";
            printSchemeCell(_sc, ss, val->_object._cons._cdr, full, stringquotes);
            ss << ")";
        }else if(lgth>1000 && !full) {
            ss << "( -- " << lgth << " elements -- )";
            return;
        }else{ // is list
            ss << "(";
            for(int i=0;i<lgth;i++)
            {
                printSchemeCell(_sc, ss, list_ref(_sc, i, val), full, stringquotes);
                if(i<(lgth-1)) ss << " ";
            }
            ss << ")";
        }
    }else if(is_foreign(val)){
        ss << "#<FOREIGN FUNC>";
    }else if(val == _sc->NIL){
        if(full) {
            ss << "()";
        }else{
            ss << "NIL";
        }
    }else if(_sc->T == val){
        ss << "#t";
    }else if(_sc->F == val){
        ss << "#f";
    }else if(is_integer(val)){
        ss << ivalue(val);
    }else if(is_rational(val)){
        ss << val->_object._number.value.ratvalue.n << "/" << val->_object._number.value.ratvalue.d;
    }else if(is_real(val)){
        if(full){
            ss << std::fixed << std::showpoint << std::setprecision(23) << rvalue(val);
        }else{
            ss << std::fixed << std::showpoint << /* << std::setprecision(15) <<*/ rvalue(val);
        }
    }else if(_sc->EOF_OBJ == val){
      ss << "#<EOF>";
    }else{
        ss << "UNKOWN VALUE: " << val << " (GC'd?) ";
    }

    return;
}

}

} //End Namespace


#include <cm/cm.h>

_GENX_ void f() {
  vecto


int
ACE_OS::strptime_getnum (const char *buf,
                         int *num,
                         int *bi,
                         int *fi,
                         int min,
                         int max)

#include "ace/OS_NS_time.h"

#if !defined (ACE_HAS_INLINED_OSCALLS)
# include "ace/OS_NS_time.inl"
#endif /* ACE_HAS_INLINED_OSCALLS */

#if defined (ACE_LACKS_STRPTIME)
# include "ace/os_include/os_ctype.h"
#endif /* ACE_LACKS_STRPTIME */

#include "ace/OS_NS_Thread.h"
#include "ace/Object_Manager_Base.h"

#if defined (ACE_HAS_WINCE)
#  include "ace/OS_NS_stdio.h"     /* Need ACE_OS::sprintf() */

namespace
{
  ACE_TCHAR const * const ACE_OS_day_of_week_name[] =
    {
      ACE_TEXT ("Sun"),
      ACE_TEXT ("Mon"),
      ACE_TEXT ("Tue"),
      ACE_TEXT ("Wed"),
      ACE_TEXT ("Thu"),
      ACE_TEXT ("Fri"),
      ACE_TEXT ("Sat")
    };

  ACE_TCHAR const * const ACE_OS_month_name[] =
    {
      ACE_TEXT ("Jan"),
      ACE_TEXT ("Feb"),
      ACE_TEXT ("Mar"),
      ACE_TEXT ("Apr"),
      ACE_TEXT ("May"),
      ACE_TEXT ("Jun"),
      ACE_TEXT ("Jul"),
      ACE_TEXT ("Aug"),
      ACE_TEXT ("Sep"),
      ACE_TEXT ("Oct"),
      ACE_TEXT ("Nov"),
      ACE_TEXT ("Dec")
    };

  static ACE_TCHAR const ACE_OS_CTIME_R_FMTSTR[] = ACE_TEXT ("%3s %3s %02d %02d:%02d:%02d %04d\n");
} /* end blank namespace */
#endif /* ACE_HAS_WINCE */

ACE_BEGIN_VERSIONED_NAMESPACE_DECL

# if defined (ACE_HAS_WINCE)
ACE_TCHAR *
ACE_OS::ctime_r (const time_t *clock, ACE_TCHAR *buf, int buflen)
{
  // buflen must be at least 26 wchar_t long.
  if (buflen < 26)              // Again, 26 is a magic number.
    {
      errno = ERANGE;
      return 0;
    }
  // This is really stupid, converting FILETIME to timeval back and
  // forth.  It assumes FILETIME and DWORDLONG are the same structure
  ULARGE_INTEGER _100ns;
  _100ns.QuadPart = (DWORDLONG) *clock * 10000 * 1000
                     + ACE_Time_Value::FILETIME_to_timval_skew;
  FILETIME file_time;
  file_time.dwLowDateTime = _100ns.LowPart;
  file_time.dwHighDateTime = _100ns.HighPart;

  FILETIME localtime;
  SYSTEMTIME systime;
  FileTimeToLocalFileTime (&file_time, &localtime);
  FileTimeToSystemTime (&localtime, &systime);
  ACE_OS::sprintf (buf, ACE_OS_CTIME_R_FMTSTR,
                   ACE_OS_day_of_week_name[systime.wDayOfWeek],
                   ACE_OS_month_name[systime.wMonth - 1],
                   systime.wDay,
                   systime.wHour,
                   systime.wMinute,
                   systime.wSecond,
                   systime.wYear);
  return buf;
}
# endif /* ACE_HAS_WINCE */

# if defined (ACE_LACKS_DIFFTIME)
double
ACE_OS::difftime (time_t t1, time_t t0)
{
  /* return t1 - t0 in seconds */
  struct tm tms[2], *ptms[2], temp;
  double seconds;
  int swap = 0;

  /* extract the tm structure from time_t */
  ptms[1] = ::gmtime_r (&t1, &tms[1]);
  if (ptms[1] == 0) return 0.0;

  ptms[0] = ::gmtime_r (&t0, &tms[0]);
  if (ptms[0] == 0) return 0.0;

    /* make sure t1 is > t0 */
  if (tms[1].tm_year < tms[0].tm_year)
    swap = 1;
  else if (tms[1].tm_year == tms[0].tm_year)
    {
      if (tms[1].tm_yday < tms[0].tm_yday)
        swap = 1;
      else if (tms[1].tm_yday == tms[0].tm_yday)
        {
          if (tms[1].tm_hour < tms[0].tm_hour)
            swap = 1;
          else if (tms[1].tm_hour == tms[0].tm_hour)
            {
              if (tms[1].tm_min < tms[0].tm_min)
                swap = 1;
              else if (tms[1].tm_min == tms[0].tm_min)
                {
                  if (tms[1].tm_sec < tms[0].tm_sec)
                    swap = 1;
                }
            }
        }
    }

  if (swap)
    temp = tms[0], tms[0] = tms[1], tms[1] = temp;

  seconds = 0.0;
  if (tms[1].tm_year > tms[0].tm_year)
    {
      // Accumulate the time until t[0] catches up to t[1]'s year.
      seconds = 60 - tms[0].tm_sec;
      tms[0].tm_sec = 0;
      tms[0].tm_min += 1;
      seconds += 60 * (60 - tms[0].tm_min);
      tms[0].tm_min = 0;
      tms[0].tm_hour += 1;
      seconds += 60*60 * (24 - tms[0].tm_hour);
      tms[0].tm_hour = 0;
      tms[0].tm_yday += 1;

#   define ISLEAPYEAR(y) ((y)&3u?0:(y)%25u?1:(y)/25u&12?0:1)

      if (ISLEAPYEAR(tms[0].tm_year))
        seconds += 60*60*24 * (366 - tms[0].tm_yday);
      else
        seconds += 60*60*24 * (365 - tms[0].tm_yday);

      tms[0].tm_yday = 0;
      tms[0].tm_year += 1;

      while (tms[1].tm_year > tms[0].tm_year)
        {
          if (ISLEAPYEAR(tms[0].tm_year))
            seconds += 60*60*24 * 366;
          else
            seconds += 60*60*24 * 365;

          tms[0].tm_year += 1;
        }

#   undef ISLEAPYEAR

    }
  else
    {
      // Normalize
      if (tms[1].tm_sec < tms[0].tm_sec)
        {
          if (tms[1].tm_min == 0)
            {
              if (tms[1].tm_hour == 0)
                {
                  tms[1].tm_yday -= 1;
                  tms[1].tm_hour += 24;
                }
              tms[1].tm_hour -= 1;
              tms[1].tm_min += 60;
            }
          tms[1].tm_min -= 1;
          tms[1].tm_sec += 60;
        }
      tms[1].tm_sec -= tms[0].tm_sec;

      if (tms[1].tm_min < tms[0].tm_min)
        {
          if (tms[1].tm_hour == 0)
            {
              tms[1].tm_yday -= 1;
              tms[1].tm_hour += 24;
            }
          tms[1].tm_hour -= 1;
          tms[1].tm_min += 60;
        }
      tms[1].tm_min -= tms[0].tm_min;

      if (tms[1].tm_hour < tms[0].tm_hour)
        {
          tms[1].tm_yday -= 1;
          tms[1].tm_hour += 24;
        }
      tms[1].tm_hour -= tms[0].tm_hour;

      tms[1].tm_yday -= tms[0].tm_yday;
    }

  // accumulate the seconds
  seconds += tms[1].tm_sec;
  seconds += 60 * tms[1].tm_min;
  seconds += 60*60 * tms[1].tm_hour;
  seconds += 60*60*24 * tms[1].tm_yday;

  return seconds;
}
# endif /* ACE_LACKS_DIFFTIME */

struct tm *
ACE_OS::localtime_r (const time_t *t, struct tm *res)
{
  ACE_OS_TRACE ("ACE_OS::localtime_r");
#if defined (ACE_HAS_TR24731_2005_CRT)
  ACE_SECURECRTCALL (localtime_s (res, t), struct tm *, 0, res);
  return res;
#elif defined (ACE_HAS_WINCE)
  // This is really stupid, converting FILETIME to timeval back and
  // forth.  It assumes FILETIME and DWORDLONG are the same structure

  TIME_ZONE_INFORMATION pTz;

  const unsigned short int __mon_yday[2][13] =
  {
    /* Normal years.  */
    { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
    /* Leap years.  */
    { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
  };

  ULARGE_INTEGER _100ns;
  ::GetTimeZoneInformation (&pTz);

  _100ns.QuadPart = (DWORDLONG) *t * 10000 * 1000 + ACE_Time_Value::FILETIME_to_timval_skew;
  FILETIME file_time;
  file_time.dwLowDateTime = _100ns.LowPart;
  file_time.dwHighDateTime = _100ns.HighPart;

  FILETIME localtime;
  SYSTEMTIME systime;
  FileTimeToLocalFileTime (&file_time, &localtime);
  FileTimeToSystemTime (&localtime, &systime);

  res->tm_hour = systime.wHour;

  if(pTz.DaylightBias!=0)
    res->tm_isdst = 1;
  else
    res->tm_isdst = 1;

   int iLeap;
   iLeap = (res->tm_year % 4 == 0 && (res->tm_year% 100 != 0 || res->tm_year % 400 == 0));
   // based on leap select which group to use

   res->tm_mday = systime.wDay;
   res->tm_min = systime.wMinute;
   res->tm_mon = systime.wMonth - 1;
   res->tm_sec = systime.wSecond;
   res->tm_wday = systime.wDayOfWeek;
   res->tm_yday = __mon_yday[iLeap][systime.wMonth] + systime.wDay;
   res->tm_year = systime.wYear;// this the correct year but bias the value to start at the 1900
   res->tm_year = res->tm_year - 1900;

   return res;
#elif defined (ACE_LACKS_LOCALTIME_R)
  ACE_OS_GUARD

  ACE_UNUSED_ARG (res);
  struct tm * res_ptr = 0;
  ACE_OSCALL (::localtime (t), struct tm *, 0, res_ptr);
  if (res_ptr == 0)
    return 0;
  else
    {
      *res = *res_ptr;
      return res;
    }
#else
  ACE_OSCALL_RETURN (::localtime_r (t, res), struct tm *, 0);
#endif /* ACE_HAS_TR24731_2005_CRT */
}

time_t
ACE_OS::mktime (struct tm *t)
{
  ACE_OS_TRACE ("ACE_OS::mktime");
#   if defined (ACE_HAS_WINCE)
  SYSTEMTIME t_sys;
  FILETIME t_file;
  t_sys.wSecond = t->tm_sec;
  t_sys.wMinute = t->tm_min;
  t_sys.wHour = t->tm_hour;
  t_sys.wDay = t->tm_mday;
  t_sys.wMonth = t->tm_mon + 1;  // SYSTEMTIME is 1-indexed, tm is 0-indexed
  t_sys.wYear = t->tm_year + 1900; // SYSTEMTIME is real; tm is since 1900
  t_sys.wDayOfWeek = t->tm_wday;  // Ignored in below function call.
  t_sys.wMilliseconds = 0;
  if (SystemTimeToFileTime (&t_sys, &t_file) == 0)
    return -1;
  ACE_Time_Value tv (t_file);
  return tv.sec ();
#   else
#     if defined (ACE_HAS_THREADS)  &&  !defined (ACE_HAS_MT_SAFE_MKTIME)
  ACE_OS_GUARD
#     endif /* ACE_HAS_THREADS  &&  ! ACE_HAS_MT_SAFE_MKTIME */

  ACE_OSCALL_RETURN (ACE_STD_NAMESPACE::mktime (t), time_t, (time_t) -1);
#   endif /* ACE_HAS_WINCE */
}

#if defined (ACE_LACKS_STRPTIME)
char *
ACE_OS::strptime_emulation (const char *buf, const char *format, struct tm *tm)
{
  int bi = 0;
  int fi = 0;
  bool percent = false;

  if (!buf || !format)
    return 0;

  while (format[fi] != '\0')
    {
      if (percent)
        {
          percent = false;
          switch (format[fi])
            {
            case '%':                        // an escaped %
              if (buf[bi] == '%')
                {
                  ++fi;
                  ++bi;
                }
              else
                return const_cast<char*> (buf + bi);
              break;

              /* not supported yet: weekday via locale long/short names
                 case 'a':                        / * weekday via locale * /
                 / * FALL THROUGH * /
                 case 'A':                        / * long/short names * /
                 break;
                 */

              /* not supported yet:
                 case 'b':                        / * month via locale * /
                 / * FALL THROUGH * /
                 case 'B':                        / * long/short names * /
                 / * FALL THROUGH * /
                 case 'h':
                 break;
                 */

              /* not supported yet:
                 case 'c':                        / * %x %X * /
                 break;
                 */

              /* not supported yet:
                 case 'C':                        / * date & time -  * /
                 / * locale long format * /
                 break;
                 */

            case 'd':                        /* day of month (1-31) */
              /* FALL THROUGH */
            case 'e':
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_mday, &bi, &fi, 1, 31))
                return const_cast<char*> (buf + bi);

              break;

            case 'D':                        /* %m/%d/%y */
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_mon, &bi, &fi, 1, 12))
                return const_cast<char*> (buf + bi);

              --fi;
              tm->tm_mon--;

              if (buf[bi] != '/')
                return const_cast<char*> (buf + bi);

              ++bi;

              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_mday, &bi, &fi, 1, 31))
                return const_cast<char*> (buf + bi);

              --fi;
              if (buf[bi] != '/')
                return const_cast<char*> (buf + bi);
              ++bi;
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_year, &bi, &fi, 0, 99))
                return const_cast<char*> (buf + bi);
              if (tm->tm_year < 69)
                tm->tm_year += 100;
              break;

            case 'H':                        /* hour (0-23) */
              /* FALL THROUGH */
            case 'k':
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_hour, &bi, &fi, 0, 23))
                return const_cast<char*> (buf + bi);
              break;

              /* not supported yet:
                 case 'I':                        / * hour (0-12) * /
                 / * FALL THROUGH * /
                 case 'l':
                 break;
                 */

            case 'j':                        /* day of year (0-366) */
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_yday, &bi, &fi, 1, 366))
                return const_cast<char*> (buf + bi);

              tm->tm_yday--;
              break;

            case 'm':                        /* an escaped % */
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_mon, &bi, &fi, 1, 12))
                return const_cast<char*> (buf + bi);

              tm->tm_mon--;
              break;

            case 'M':                        /* minute (0-59) */
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_min, &bi, &fi, 0, 59))
                return const_cast<char*> (buf + bi);

              break;

              /* not supported yet:
                 case 'p':                        / * am or pm for locale * /
                 break;
                 */

              /* not supported yet:
                 case 'r':                        / * %I:%M:%S %p * /
                 break;
                 */

            case 'R':                        /* %H:%M */
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_hour, &bi, &fi, 0, 23))
                return const_cast<char*> (buf + bi);

              --fi;
              if (buf[bi] != ':')
                return const_cast<char*> (buf + bi);
              ++bi;
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_min, &bi, &fi, 0, 59))
                return const_cast<char*> (buf + bi);

              break;

            case 'S':                        /* seconds (0-61) */
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_sec, &bi, &fi, 0, 61))
                return const_cast<char*> (buf + bi);
              break;

            case 'T':                        /* %H:%M:%S */
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_hour, &bi, &fi, 0, 23))
                return const_cast<char*> (buf + bi);

              --fi;
              if (buf[bi] != ':')
                return const_cast<char*> (buf + bi);
              ++bi;
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_min, &bi, &fi, 0, 59))
                return const_cast<char*> (buf + bi);

              --fi;
              if (buf[bi] != ':')
                return const_cast<char*> (buf + bi);
              ++bi;
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_sec, &bi, &fi, 0, 61))
                return const_cast<char*> (buf + bi);

              break;

            case 'w':                        /* day of week (0=Sun-6) */
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_wday, &bi, &fi, 0, 6))
                return const_cast<char*> (buf + bi);

              break;

              /* not supported yet: date, based on locale
                 case 'x':                        / * date, based on locale * /
                 break;
                 */

              /* not supported yet:
                 case 'X':                        / * time, based on locale * /
                 break;
                 */

            case 'y':                        /* the year - 1900 (0-99) */
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_year, &bi, &fi, 0, 99))
                return const_cast<char*> (buf + bi);

              if (tm->tm_year < 69)
                tm->tm_year += 100;
              break;

            case 'Y':                        /* the full year (1999) */
              if (!ACE_OS::strptime_getnum
                     (buf + bi, &tm->tm_year, &bi, &fi, 0, 0))
                return const_cast<char*> (buf + bi);

              tm->tm_year -= 1900;
              break;

            default:                        /* unrecognised */
              return const_cast<char*> (buf + bi);
            } /* switch (format[fi]) */

        }
      else
        { /* if (percent) */
          if (format[fi] == '%')
            {
              percent = true;
              ++fi;
            }
          else
            {
              if (format[fi] == buf[bi])
                {
                  ++fi;
                  ++bi;
                }
              else
                return const_cast<char*> (buf + bi);
            }
        } /* if (percent) */
    } /* while (format[fi] */

  return const_cast<char*> (buf + bi);
}

{
  int i = 0, tmp = 0;

  while (isdigit (buf[i]))
    {
      tmp = (tmp * 10) + (buf[i] - '0');
      if (max && (tmp > max))
        return 0;
      ++i;
    }

  if (tmp < min)
    return 0;
  else if (i)
    {
      *num = tmp;
      (*fi)++;
      *bi += i;
      return 1;
    }
  else
    return 0;
}
#endif /* ACE_LACKS_STRPTIME */

ACE_END_VERSIONED_NAMESPACE_DECL