File: littler.c

package info (click to toggle)
littler 0.2.1-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 668 kB
  • ctags: 77
  • sloc: sh: 4,142; ansic: 511; makefile: 31
file content (683 lines) | stat: -rw-r--r-- 22,898 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
/*  -*- mode: C; c-indent-level: 8; c-basic-offset: 4; indent-tabs-mode: nil; -*-
 *
 *  littler - Provides hash-bang (#!) capability for R (www.r-project.org)
 *
 *  Copyright (C) 2006 - 2014  Jeffrey Horner and Dirk Eddelbuettel
 *
 *  littler is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program 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 General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

#include <getopt.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>

#include "config.h"
#include "gitversion.h"
#include "autoloads.h"
#include "littler.h"

#include <R.h>
#include <Rembedded.h>
#include <Rversion.h>
#include <Rdefines.h>
#define R_INTERFACE_PTRS
#include <Rinterface.h>
#include <R_ext/Parse.h>
#include <R_ext/RStartup.h>

int verbose=0;

/* PACKAGE, VERSION, ... are being filled by autoconf and friends via config.h */
const char *programName = PACKAGE;
const char *binaryName = "r";

#ifndef HAVE_SETENV
int  setenv(char *name, char *value, int clobber){
    char   *cp;

    if (clobber == 0 && getenv(name) != 0)
        return (0);
    if ((cp = malloc(strlen(name) + strlen(value) + 2)) == 0)
        return (1);
    sprintf(cp, "%s=%s", name, value);
    return (putenv(cp));
}
#endif 

int source(char *file){
    SEXP expr, s, f, p;
    int errorOccurred;

    /* Find source function */
    s = Rf_findFun(Rf_install("source"), R_GlobalEnv);
    PROTECT(s);

    /* Make file argument */
    PROTECT(f = NEW_CHARACTER(1));
    SET_STRING_ELT(f, 0, COPY_TO_USER_STRING(file));

    /* Make print.eval argument */
    PROTECT(p = NEW_LOGICAL(1));
    LOGICAL_DATA(p)[0] = (verbose)? TRUE : FALSE;

    /* expression source(f,print.eval=p) */
    PROTECT(expr = allocVector(LANGSXP,3));
    SETCAR(expr,s); 
    SETCAR(CDR(expr),f);
    SETCAR(CDR(CDR(expr)), p);
    SET_TAG(CDR(CDR(expr)), Rf_install("print.eval"));
    
    errorOccurred=0;
    R_tryEval(expr,NULL,&errorOccurred);
    UNPROTECT(4);

    return errorOccurred;
}

/* Autoload default packages and names from autoloads.h
 *
 * This function behaves in almost every way like
 * R's autoload:
 * function (name, package, reset = FALSE, ...)
 * {
 *     if (!reset && exists(name, envir = .GlobalEnv, inherits = FALSE))
 *        stop("an object with that name already exists")
 *     m <- match.call()
 *     m[[1]] <- as.name("list")
 *     newcall <- eval(m, parent.frame())
 *     newcall <- as.call(c(as.name("autoloader"), newcall))
 *     newcall$reset <- NULL
 *     if (is.na(match(package, .Autoloaded)))
 *        assign(".Autoloaded", c(package, .Autoloaded), env = .AutoloadEnv)
 *     do.call("delayedAssign", list(name, newcall, .GlobalEnv,
 *                                                         .AutoloadEnv))
 *     invisible()
 * }
 *
 * What's missing is the updating of the string vector .Autoloaded with the list
 * of packages, which by my code analysis is useless and only for informational
 * purposes.
 *
 */
void autoloads(void){
    SEXP da, dacall, al, alcall, AutoloadEnv, name, package;
    int i,j, idx=0, errorOccurred, ptct;
    
    /* delayedAssign call*/
    PROTECT(da = Rf_findFun(Rf_install("delayedAssign"), R_GlobalEnv));
    PROTECT(AutoloadEnv = Rf_findVar(Rf_install(".AutoloadEnv"), R_GlobalEnv));
    if (AutoloadEnv == R_NilValue){
        fprintf(stderr,"%s: Cannot find .AutoloadEnv!\n", programName);
        exit(1);
    }
    PROTECT(dacall = allocVector(LANGSXP,5));
    SETCAR(dacall,da);
    /* SETCAR(CDR(dacall),name); */          /* arg1: assigned in loop */
    /* SETCAR(CDR(CDR(dacall)),alcall); */  /* arg2: assigned in loop */
    SETCAR(CDR(CDR(CDR(dacall))),R_GlobalEnv); /* arg3 */
    SETCAR(CDR(CDR(CDR(CDR(dacall)))),AutoloadEnv); /* arg3 */


    /* autoloader call */
    PROTECT(al = Rf_findFun(Rf_install("autoloader"), R_GlobalEnv));
    PROTECT(alcall = allocVector(LANGSXP,3));
    SET_TAG(alcall, R_NilValue); /* just like do_ascall() does */
    SETCAR(alcall,al);
    /* SETCAR(CDR(alcall),name); */          /* arg1: assigned in loop */
    /* SETCAR(CDR(CDR(alcall)),package); */  /* arg2: assigned in loop */

    ptct = 5;
    for(i = 0; i < packc; i++){
        idx += (i != 0)? packobjc[i-1] : 0;
        for (j = 0; j < packobjc[i]; j++){
            /*printf("autload(%s,%s)\n",packobj[idx+j],pack[i]);*/
            
            PROTECT(name = NEW_CHARACTER(1));
            PROTECT(package = NEW_CHARACTER(1));
            SET_STRING_ELT(name, 0, COPY_TO_USER_STRING(packobj[idx+j]));
            SET_STRING_ELT(package, 0, COPY_TO_USER_STRING(pack[i]));
            
            /* Set up autoloader call */
            PROTECT(alcall = allocVector(LANGSXP,3));
            SET_TAG(alcall, R_NilValue); /* just like do_ascall() does */
            SETCAR(alcall,al);
            SETCAR(CDR(alcall),name);
            SETCAR(CDR(CDR(alcall)),package);

            /* Setup delayedAssign call */
            SETCAR(CDR(dacall),name);
            SETCAR(CDR(CDR(dacall)),alcall);
            
            R_tryEval(dacall,R_GlobalEnv,&errorOccurred);
            if (errorOccurred){
                fprintf(stderr,"%s: Error calling delayedAssign!\n", programName);
                exit(1);
            }
            
            ptct += 3;
        }
    }
    UNPROTECT(ptct);
}

/* Line reading code */
typedef struct membuf_st {
    int size;
    int count;
    unsigned char *buf;
} *membuf_t;

membuf_t init_membuf(int sizebytes){
    membuf_t lb = malloc(sizebytes+sizeof(struct membuf_st));

    if (lb == NULL) {
        fprintf(stderr,"%s: init_membuf() failed! Exiting!!!\n\n", programName);
        exit(1);
        return NULL; /* unreached */
    }

    lb->size = sizebytes;
    lb->count = 0;
    lb->buf = (unsigned char *)lb+sizeof(struct membuf_st);

    return lb;
}

void destroy_membuf(membuf_t lb){
    free(lb);
}

/* Use power of 2 resizing */
membuf_t resize_membuf(membuf_t *plb){
    membuf_t lb = *plb;
    lb = *plb = realloc(lb,lb->size*2+sizeof(struct membuf_st));
    if (lb == NULL) {
        fprintf(stderr,"%s: init_membuf() failed! Exiting!!!\n\n", programName);
        exit(1);
        return NULL; /* unreached */
    }

    lb->size =  lb->size * 2;
    lb->buf = (unsigned char *)lb+sizeof(struct membuf_st);

    return lb;
}

membuf_t rewind_membuf(membuf_t *mb){
    (*mb)->count = 0;
    return *mb;
}

membuf_t add_to_membuf(membuf_t *pmb,char *buf){
    membuf_t mb = *pmb;
    int buflen = strlen(buf);

    while ((buflen + (mb->count)) >= mb->size){
        mb = *pmb = resize_membuf(pmb);
    }

    memcpy(mb->buf+mb->count,buf,buflen);
    mb->buf[mb->count+buflen] = '\0';
    mb->count += buflen;

    return mb;
}


/* returns 1 on reading another line or until EOF, 0 on EOF */
int readline_stdin(membuf_t *plb){
    membuf_t lb = *plb;
    unsigned int offset=0;
    char *str;

    do {
        lb->buf[lb->size-2] = '\0'; /* mark last char position */
        str = fgets((char*)lb->buf+offset,lb->size-offset,stdin);

        /* EOF or error */ 
        if (str == NULL){ 
            return (offset)? 1 : 0;
        }

        /* Did we read a whole line? */
        if (lb->buf[lb->size-2] != '\0' && lb->buf[lb->size-2] != '\n'){
            /* No. read again. */
            offset = lb->size-1;
            lb = *plb = resize_membuf(plb);
        } else {
            /* Yes. return */
            return 1;
        }
    } while(1);	
}

int parse_eval(membuf_t *pmb, char *line, int lineno){
    membuf_t mb = *pmb;
    ParseStatus status;
    SEXP cmdSexp, cmdexpr, ans = R_NilValue;
    int i, errorOccurred;

    mb = *pmb = add_to_membuf(pmb,line);

    PROTECT(cmdSexp = allocVector(STRSXP, 1));
    SET_STRING_ELT(cmdSexp, 0, mkChar((char*)mb->buf));

    /* R_ParseVector gets a new argument in R 2.5.x */
    cmdexpr = PROTECT(R_ParseVector(cmdSexp, -1, &status, R_NilValue));

    switch (status){
    case PARSE_OK:
        /* Loop is needed here as EXPSEXP might be of length > 1 */
        for(i = 0; i < length(cmdexpr); i++){
            ans = R_tryEval(VECTOR_ELT(cmdexpr, i),NULL, &errorOccurred);
            if (errorOccurred) { 
                UNPROTECT(2);
                return 1;
            }
            if (verbose) {
                PrintValue(ans);
            }
        }
        mb = *pmb = rewind_membuf(pmb);
        break;
    case PARSE_INCOMPLETE:
        fprintf(stderr, "%s: Incomplete Line! Need more code! (%d)\n", programName, status);
        UNPROTECT(2);
        return 1;
        break;
    case PARSE_NULL:
        fprintf(stderr, "%s: ParseStatus is null (%d)\n", programName, status);
        UNPROTECT(2);
        return 1;
        break;
    case PARSE_ERROR:
        fprintf(stderr,"Parse Error line %d: \"%s\"\n", lineno, line);
        UNPROTECT(2);
        return 1;
        break;
    case PARSE_EOF:
        fprintf(stderr, "%s: EOF reached (%d)\n", programName, status);
        break;
    default:
        fprintf(stderr, "%s: ParseStatus is not documented %d\n", programName, status);
        UNPROTECT(2);
        return 1;
        break;
    }
    UNPROTECT(2);
    return 0;
}

extern char *R_TempDir;
int perSessionTempDir = FALSE;	/* by default, r differs from R and defaults to /tmp unless env.vars set, or flag chosen */

void littler_InitTempDir()
{
    char *tmp;

    if (perSessionTempDir) return; 	/* use a per-session temporary directory by following R */

    tmp = getenv("TMPDIR");		/* set tmp to TMPDIR, or TMP, or TEMP, or "/tmp" */
    if (tmp == NULL) {
        tmp = getenv("TMP");
        if (tmp == NULL) { 
            tmp = getenv("TEMP");
            if (tmp == NULL) 
                tmp = "/tmp";
        }
    }

    R_TempDir=tmp;

    if (setenv("R_SESSION_TMPDIR",tmp,1) != 0){
        perror("Fatal Error: couldn't set/replace R_SESSION_TMPDIR!");
        exit(1);
    }
}

/* littler exit */
void littler_CleanUp(SA_TYPE saveact, int status, int runLast){
    R_dot_Last();
    R_RunExitFinalizers();
    if (perSessionTempDir) R_CleanTempDir();
    fpu_setup(FALSE);
    Rf_endEmbeddedR(0);
    exit(status);
}

void showHelpAndExit() {
    printf("\n" 						
           "Usage: %s [options] [-|file]"
           "\n\n"
           "Launch GNU R to execute the R commands supplied in the specified file, or\n"
           "from stdin if '-' is used. Suitable for so-called shebang '#!/'-line scripts.\n"
           "\n"
           "Options:\n"
           "  -h, --help           Give this help list\n"
           "      --usage          Give a short usage message\n"
           "  -V, --version        Show the version number\n"
           "  -v, --vanilla        Pass the '--vanilla' option to R\n"  
           "  -t, --rtemp          Use per-session temporary directory as R does\n"
           "  -i, --interactive    Let interactive() return 'true' rather than 'false'\n"
           "  -q, --quick          Skip autoload / delayed assign of default libraries\n"
           "  -p, --verbose        Print the value of expressions to the console\n"  
           "  -l, --packages list  Load the R packages from the comma-separated 'list'\n"	
           "  -d, --datastdin      Prepend command to load 'X' as csv from stdin\n"	
           "  -e, --eval  expr     Let R evaluate 'expr'\n"
           "\n\n",
           binaryName);
    exit(-1);
}

void showVersionAndExit() {
    char txt[64];
    printf("%s ('%s') version %s\n\ngit revision %s as of %s\nbuilt at %s on %s\n", 
           binaryName, programName, VERSION, 
           gitrevision, gitdate, compiletime, compiledate);
    printf("using GNU R ");
    snprintf(txt, 63, "%d", R_SVN_REVISION);
    if (strcmp(txt, "unknown")==0) {
        printf("Version %s.%s %s (%s-%s-%s)",
               R_MAJOR, R_MINOR, R_STATUS, R_YEAR, R_MONTH, R_DAY);
    } else {
        if (strlen(R_STATUS)==0) {
            printf("Version %s.%s (%s-%s-%s)",
                   R_MAJOR, R_MINOR, R_YEAR, R_MONTH, R_DAY);
        }
        else{
            printf("Version %s.%s %s (%s-%s-%s r%d)",
                   R_MAJOR, R_MINOR, R_STATUS, R_YEAR, R_MONTH, R_DAY,
                   R_SVN_REVISION);
        }
    }
    printf("\n\nCopyright (C) 2006 - 2014  Jeffrey Horner and Dirk Eddelbuettel\n"
           "\n"
           "%s is free software and comes with ABSOLUTELY NO WARRANTY.\n"
           "You are welcome to redistribute it under the terms of the\n"
           "GNU General Public License.  For more information about\n"
           "these matters, see http://www.gnu.org/copyleft/gpl.html.\n\n",
           binaryName);
	exit(0);       
}

void showUsageAndExit() {
    printf("\n" 						
           "%s (aka '%s') can be used in four main modes.\n\n"
           "The first is via the so-called 'shebang' support it provides for GNU R.\n"
           "Suppose '%s' is installed in /usr/local/bin/%s. Then the first line of a\n"
           "script can be written as \"#!/usr/local/bin/%s\" and the rest of the file\n"
           "can contain standard R commands.  By setting executable permissions\n"
           "on the file, one can now create executable R scripts.\n\n" 
           "The second is to supply a filename with commands that are to be\n"
           "evaluated.\n\n"
           "The third use is in standard compound command-line expressions common\n" 
           "under Unix (so called 'command pipes') as '%s' can take arguments\n"
           "from stdin if the special filename '-' is used to select stdin.\n\n"
           "The fourth use is in on-the-fly evaluation of R expressions supplied\n"
           "via the -e or --eval options to provide a quick R expression tester\n"
           "and calculator.\n\n"
           "More documentation is provided in the '%s' manual page and via\n"
           "the tests directory in the sources.\n\n",
           binaryName, programName, binaryName, binaryName, binaryName,  
           programName, binaryName);
    exit(0);       
}

/* set seed for tempfile()  */
void init_rand()
{
    unsigned int seed;
#if HAVE_GETTIMEOFDAY
    {
        struct timeval tv;
        gettimeofday (&tv, NULL);
        /* changed uint64_t to unsigned int. Need to figure out why PBR used that instead. */
        seed = ((unsigned int) tv.tv_usec << 16) ^ tv.tv_sec;
    }
#elif HAVE_TIME
    seed = (unsigned int) time(NULL);
#else
    /* unlikely, but use random contents */
#endif
    srand(seed);
}

int main(int argc, char **argv){

    /* R embedded arguments, and optional arguments to be picked via cmdline switches */
    char *R_argv[] = {(char*)programName, "--gui=none", "--no-restore", "--no-save", "--no-readline", "--silent", "", ""};
    char *R_argv_opt[] = {"--vanilla", "--slave"};
    int R_argc = (sizeof(R_argv) - sizeof(R_argv_opt) ) / sizeof(R_argv[0]);
    int i, nargv, c, optpos=0, vanilla=0, quick=0, interactive=0, datastdin=0;
    char *evalstr = NULL;
    char *libstr = NULL;
    SEXP s_argv;
    structRstart Rst;
    char *datastdincmd = "X <- read.csv(file(\"stdin\"), stringsAsFactors=FALSE);";

    static struct option optargs[] = {
        {"help",         no_argument,       NULL, 'h'}, 	/* --help also has short option -h */
        {"usage",        no_argument,       0,    0},
        {"version",      no_argument,       NULL, 'V'},
        {"vanilla",      no_argument,       NULL, 'v'},
        {"eval",         required_argument, NULL, 'e'},
        {"packages",     required_argument, NULL, 'l'},
        {"verbose",      no_argument,       NULL, 'p'},
        {"rtemp",        no_argument,       NULL, 't'},
        {"quick",        no_argument,       NULL, 'q'},
        {"interactive",  no_argument,       NULL, 'i'},
        {"datastdin",    no_argument,       NULL, 'd'},
        {0, 0, 0, 0}
    };
    while ((c = getopt_long(argc, argv, "+hVve:npl:tqid", optargs, &optpos)) != -1) {
        switch (c) {	
        case 0:				/* numeric 0 is code for a long option */
            /* printf ("Got option %s %d", optargs[optpos].name, optpos);*/
            switch (optpos) {		/* so switch on the position in the optargs struct */
					/* cases 0, 2, and 3 can't happen as they are covered by the '-h', */ 
					/* '-V', and '-v' equivalences */
            case 1:
                showUsageAndExit();
                break;				/* never reached */
            case 5:
                verbose = 1;
                break;
            default:
                printf("Uncovered option position '%d'. Try `%s --help' for help\n", 
                       optpos, programName);
                exit(-1);
            }
            break;
        case 'h':			/* -h is the sole short option, cf getopt_long() call */
            showHelpAndExit();
            break;  			/* never reached */
        case 'e':
            evalstr = optarg;
            break;
        case 'l':
            libstr = optarg;
            break;
        case 'v':	
            vanilla=1;
            break;
        case 'p':	
            verbose=1;
            break;
        case 'V':
            showVersionAndExit();
            break;  			/* never reached */
        case 't':
            perSessionTempDir=TRUE;
            break;
        case 'q':
            quick=1;
            break;
        case 'i':
            interactive=1;
            break;
        case 'd':
            datastdin=1;
            break;
        default:
            printf("Unknown option '%c'. Try `%s --help' for help\n",(char)c, programName);
            exit(-1);
        }
    }
    if (vanilla) {
        R_argv[R_argc++] = R_argv_opt[0];
    }
    if (!verbose) {
        R_argv[R_argc++] = R_argv_opt[1];
    }

#ifdef DEBUG
    printf("R_argc %d sizeof(R_argv) \n", R_argc, sizeof(R_argv));
    for (i=0; i<7; i++) {
        printf("R_argv[%d] = %s\n", i, R_argv[i]);
    }
    printf("optind %d, argc %d\n", optind, argc);
    for (i=0; i<argc; i++) {
        printf("argv[%d] = %s\n", i, argv[i]);
    }
#endif

    /* Now, argv[optind] could be a file we want to source -- if we're
     * in the 'shebang' case -- or it could be an expression from stdin.
     * So call stat(1) on it, and if its a file we will treat it as such.
     */
    struct stat sbuf;
    if (optind < argc && evalstr==NULL) { 
        if ((strcmp(argv[optind],"-") != 0) && (stat(argv[optind],&sbuf) != 0)) {
            perror(argv[optind]);
            exit(1);
        }
    }

    /* Setenv R_* env vars: insert or replace into environment.  */
    for (i = 0; R_VARS[i] != NULL; i+= 2){
        if (setenv(R_VARS[i],R_VARS[i+1],1) != 0){
            perror("ERROR: couldn't set/replace an R environment variable");
            exit(1);
        }
    }

    /* We don't require() default packages upon startup; rather, we
     * set up delayedAssign's instead. see autoloads().
     */
    if (setenv("R_DEFAULT_PACKAGES","NULL",1) != 0) {
        perror("ERROR: couldn't set/replace R_DEFAULT_PACKAGES");
        exit(1);
    }

    R_SignalHandlers = 0;			/* Don't let R set up its own signal handlers */

#ifdef CSTACK_DEFNS
    R_CStackLimit = (uintptr_t)-1;		/* Don't do any stack checking, see R Exts, '8.1.5 Threading issues' */
#endif

    littler_InitTempDir();			/* Set up temporary directoy */
    
    Rf_initEmbeddedR(R_argc, R_argv);	/* Initialize the embedded R interpreter */

    R_ReplDLLinit(); 			/* this is to populate the repl console buffers */

    if (!interactive) {			/* new in littler 0.1.3 */
        R_DefParams(&Rst);
        Rst.R_Interactive = 0;		/* sets interactive() to eval to false */
        R_SetParams(&Rst);
    }

    ptr_R_CleanUp = littler_CleanUp; 	/* R Exts, '8.1.2 Setting R callbacks */

    if (quick != 1) {			/* Unless user chose not to load libraries */
        autoloads();			/* Force all default package to be dynamically required */
    }

    /* Place any argv arguments into argv vector in Global Environment */
    /* if we have an evalstr supplied from -e|--eval, correct for it */
    if ((argc - optind - (evalstr==NULL)) >= 1) {
        int offset = (evalstr==NULL) + (strcmp(argv[optind],"-") == 0);
        /* Build string vector */
        nargv = argc - optind - offset;
        PROTECT(s_argv = allocVector(STRSXP,nargv));
        for (i = 0; i <nargv; i++){
            STRING_PTR(s_argv)[i] = mkChar(argv[i+offset+optind]);
#ifdef DEBUG
            printf("Passing %s to R\n", argv[i+offset+optind]);
#endif
        }
        UNPROTECT(1);
        setVar(install("argv"),s_argv,R_GlobalEnv);
    } else {
        setVar(install("argv"),R_NilValue,R_GlobalEnv);
    }

    init_rand();				/* for tempfile() to work correctly */

    if (libstr != NULL) {			/* if requested by user, load libraries */
        char *ptr, *token, *strptr;
        char buf[128];
        
        ptr = token = libstr;
        membuf_t pb = init_membuf(512);
        while (token != NULL) {
            token = strtok_r(ptr, ",", &strptr);
            ptr = NULL; 			/* after initial call strtok expects NULL */
            if (token != NULL) {
                snprintf(buf, 127-27-strlen(token), "suppressMessages(library(%s));", token); 
                parse_eval(&pb, buf, 1);
            }
        } 
        destroy_membuf(pb);
    }

    if (datastdin) {				/* if requested by user, read 'dat' from stdin */
        membuf_t pb = init_membuf(512);
        parse_eval(&pb, datastdincmd, 1);
        destroy_membuf(pb);
    }

    /* Now determine which R code to evaluate */
    int exit_val = 0;
    if (evalstr != NULL) {			
        /* we have a command line expression to evaluate */
        membuf_t pb = init_membuf(1024);
        exit_val = parse_eval(&pb, evalstr, 1);
        destroy_membuf(pb);
    } else if (optind < argc && (strcmp(argv[optind],"-") != 0)) {	
        /* call R function source(filename) */
        exit_val = source(argv[optind]);
    } else {
        /* Or read from stdin */
        membuf_t lb = init_membuf(1024);
        membuf_t pb = init_membuf(1024);
        int lineno = 1;
        while(readline_stdin(&lb)){
            exit_val = parse_eval(&pb,(char*)lb->buf,lineno++);
            if (exit_val) break;
        }
        destroy_membuf(lb);
        destroy_membuf(pb);
    }
    littler_CleanUp(SA_NOSAVE, exit_val, 0);
    return(0); /* not reached, but making -Wall happy */
}