1void Init_golf(void);
2#define ruby_options goruby_options
3#define ruby_run_node goruby_run_node
4#include "main.c"
5#undef ruby_options
6#undef ruby_run_node
7
8#if defined _WIN32
9#include <io.h>
10#include <fcntl.h>
11#define pipe(p) _pipe(p, 32L, _O_NOINHERIT)
12#elif defined HAVE_UNISTD_H
13#include <unistd.h>
14#endif
15
16RUBY_EXTERN void *ruby_options(int argc, char **argv);
17RUBY_EXTERN int ruby_run_node(void*);
18RUBY_EXTERN void ruby_init_ext(const char *name, void (*init)(void));
19
20static VALUE
21init_golf(VALUE arg)
22{
23    ruby_init_ext("golf", Init_golf);
24    return arg;
25}
26
27void *
28goruby_options(int argc, char **argv)
29{
30    static const char cmd[] = "END{require 'irb';IRB.start}";
31    int rw[2], infd;
32    void *ret;
33
34    if ((isatty(0) && isatty(1) && isatty(2)) && (pipe(rw) == 0)) {
35	infd = dup(0);
36	dup2(rw[0], 0);
37	close(rw[0]);
38	write(rw[1], cmd, sizeof(cmd) - 1);
39	close(rw[1]);
40	ret = ruby_options(argc, argv);
41	dup2(infd, 0);
42	close(infd);
43	return ret;
44    }
45    else {
46	return ruby_options(argc, argv);
47    }
48}
49
50int
51goruby_run_node(void *arg)
52{
53    int state;
54    if (NIL_P(rb_protect(init_golf, Qtrue, &state))) {
55	return state == EXIT_SUCCESS ? EXIT_FAILURE : state;
56    }
57    return ruby_run_node(arg);
58}
59