git @ Cat's Eye Technologies Befunge-93 / develop-2018-1 src / bef.c
develop-2018-1

Tree @develop-2018-1 (Download .tar.gz)

bef.c @develop-2018-1raw · history · blame

  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
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
/* ******************************************************************

   bef.c - The Original Befunge-93 Interpreter/Debugger in ANSI C
   v2.24

   Copyright (c)1993-2018, Chris Pressey, Cat's Eye Technologies.
   All rights reserved.

   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions
   are met:

     Redistributions of source code must retain the above copyright
     notices, this list of conditions and the following disclaimer.

     Redistributions in binary form must reproduce the above copyright
     notices, this list of conditions, and the following disclaimer in
     the documentation and/or other materials provided with the
     distribution.

     Neither the names of the copyright holders nor the names of their
     contributors may be used to endorse or promote products derived
     from this software without specific prior written permission. 

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
   ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES INCLUDING, BUT NOT
   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
   FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
   COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
   INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
   BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE.

   ******************************************************************

   Usage :

   bef [-d] [-o] [-u] [-q] [-i] [-=] [-l] [-t]
       [-r input-file] [-w output-file]
       [-s stack-file] [-y delay] <befunge-source>

      -d: visual ANSI debugging display
      -o: do not fix off-by-one error (for old sources)
      -u: & on error or EOF is undefined, not -1 (backwards compat)
      -q: produce no output except Befunge program output ('quiet')
      -i: ignore unsupported instructions
      -=: use b97-ish = directives
      -l: wrap instead of truncating long program lines (compat w/2.21)
      -t: make # at edge of playfield wrap inconsistently (compat w/2.21)
      -r: redirect input from a specified file instead of stdin
      -w: redirect output to a specified file instead of stdout
      -s: write contents of stack to log file
      -y: specify debugging delay in milliseconds

   Known to Compile Under :

        gcc 5.4.0 (Ubuntu 16.04)
        gcc 4.5.3 (NetBSD 6.1.5)
        DICE C 3.15 (AmigaDOS 1.3)
        DJGPP 2.05 gcc 8.1.0 (32-bit Protected-Mode, FreeDOS 1.1)
        Borland C++ v3.1 (16-bit, FreeDOS 1.1)
        Microsoft Visual C++ 14.15 (see NMakefile)

   Has, in the Past, been Known to Compile Under:

        Metrowerks CodeWarrior (MacOS)

   ******************************************************************

   History:

   v2.24: Sep 2018, Chris Pressey
          when & encounters an error or EOF condition it pushes
            -1 onto the stack instead of an undefined value;
            added -u option to retain old behaviour in this case
            (thanks to James Holderness for noticing and suggesting)
          support for compiling with MSVC (also by James Holderness)

   v2.23: Aug 2012, Chris Pressey
          delay given with -y now actually happens when compiled
            with compilers other than Borland C++; it's implemented
            with nanosleep() in C99, and sleep() (with one-second
            resolution) in ANSI C

   v2.22: Mar 2011, Chris Pressey
          don't insert bogus EOF/directive characters into
            playfield when loading otherwise blank source file
            (thanks to whoever sent me this patch 6 years ago)
          truncate long lines instead of wrapping them, so that
            programs that use the full 80 characters on adjacent
            lines (like mycology) can load correctly; -l disables
          make # at edge of playfield wrap and consistently skip
            a space, regardless of which edge it's on; -t disables
          unknown command-line options are reported as such
          use corrected verbiage in license (I am not a Regent)

   v2.21: Sep 2004, Chris Pressey
          display correct version number
          cleanup only, no functional changes

   v2.20, Jul 2000, Chris Pressey
          prettied up preprocessor directives a bit
          added defines for Metrowerks CodeWarrior
            so that bef will build on MacOS
          relicensed under BSD

   v2.12, Mar 1998, Chris Pressey / compiles under Borland C++ v3.1
          added -i and -= options.  You must specify -= if
            you want to use b97-esque directives or the Un*x-ish
            # comment thing, or both.
          automatically appends '.bf' to filenames containing no periods.
          explicitly pops remaining stack elements at end of execution.
          compatibility messages are displayed when quiet is not specified.
          debug mode is much improved, especially I/O under BorlandC.
          bounds checking on 'p' and 'g' instructions.

   v2.11, Jan 1998, Chris Pressey / compiles under Borland C++ v3.1
          divide by zero now produces the correct result
          improved some minor aesthetic features (messages & debug)
          ANSI is used only if not compiling under Borland C.

   v2.10: Jul 1997, Chris Pressey
          added -q command line option.
          added primitive understanding of = directive from b97 spec.
          any file with a =l directive but without =l b93 is rejected.
          also understands # as a pre-directive line prefix for
            Un*x-ish systems.

   v2.02: Jun 1997, Chris Pressey
          pads playfield with space characters.  all unread
            locations remain spaces.

   v2.01: Jun 1997, Chris Pressey
          command line switches are not case-insensitive.
          fixes gcc Segmentation Fault error.

   v2.00: Jun 1997, Chris Pressey
          combines interpreter and debugger.
          fixes ANSI error in debugger.

   v1.02: Feb 1996, Chris Pressey
          @ now pushes '@' onto the stack in stringmode instead of quitting.

   v1.01: Feb 1996, Chris Pressey
          fixes off-by-one error.

   v1.00: Sept 1993, Chris Pressey
          original Befunge-93 distribution.

   ****************************************************************** */

/********************************************************* #INCLUDE'S */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <time.h>
#if defined(__TURBOC__) || defined(__BORLANDC__) || defined(__DJGPP__)
  #define MSDOS 1
#endif
#ifdef MSDOS
#  include <dos.h>
#  include <conio.h>
#  define CONSOLE 1
#  define CURSORSHAPE 1
#endif /* MSDOS */
#ifdef __GNUC__
#  include <unistd.h>
#endif /* __GNUC__ */
#ifdef _POSIX_C_SOURCE
#  include <sys/time.h>
#endif /* _POSIX_C_SOURCE */
#ifdef __MWERKS__
#  include <console.h>
#  define CONSOLE 1
#endif /* __MWERKS__ */
#ifdef _MSC_VER
#  define sleep(s) _sleep(1000 * s)
#endif /* _MSC_VER */

/********************************************************** #DEFINE'S */

#define LINEWIDTH    80
#define PAGEHEIGHT   25

#define SCREENWIDTH  79
#define SCREENHEIGHT 22

#define DEBUGROW 24
#define cur pg[y * LINEWIDTH + x]

/********************************************************* STRUCTURES */

struct stack                    /* stack structure, for values on stack */
{
  signed long val;
  struct stack *next;
} * head;                       /* head of stack */

/*************************************************** GLOBAL VARIABLES */

char pg[LINEWIDTH * PAGEHEIGHT]; /* befunge 'page' of source */
int x = 0, y = 0;                /* x and y of the PC */
int dx = 1, dy = 0;              /* direction of the PC */
int debug = 0;                   /* flag : display ANSI debugging? */
int infile = 0, ia;              /* flag : use input file, and assoc arg? */
int outfile = 0, oa;             /* flag : use output file, and assoc arg? */
int stackfile = 0, sa;           /* flag : use stack log file, & assoc arg? */
int stringmode = 0;              /* flag : are we in string mode? */
int quiet = 0;                   /* flag : are we quiet? */
int v10err_compat = 0;           /* flag : emulate v1.0 off-by-one err? */
int undef_input_int = 0;         /* flag : undefined value on "&" err/EOF? */
int deldur = 25;                 /* debugging delay in milliseconds */
int ignore_unsupported = 0;      /* flag : ignore unsupported instructions? */
int use_b97directives = 0;       /* flag : use b97-esque directives? */
int wrap_long_program_lines = 0; /* flag : long program lines wrap? */
int inconsistent_trampoline = 0; /* flag : should # wrap inconsistently? */

/********************************************************* PROTOTYPES */

void befsleep (int);
void push (signed long val);
signed long pop (void);
void usage (void);
int main (int, char **);

/******************************************************* MAIN PROGRAM */

int main (argc, argv)
     int argc;
     char **argv;
{
  FILE *f=NULL;
  FILE *fi=NULL;
  FILE *fo=NULL;
  FILE *fs=NULL;
  int i;
  char filename[128];

#ifdef __MWERKS__
  argc = ccommand(&argv);
#endif /* __MWERKS__ */

  srand((unsigned)time(0));

  if (argc < 2)
  {
    usage();
  }
  for (i = 1; i < argc; i++)
  {
    if (argv[i][0] == '-') {
      if (!strcmp(argv[i], "-o")) { v10err_compat = 1; }
      else if (!strcmp(argv[i], "-u")) { undef_input_int = 1; }
      else if (!strcmp(argv[i], "-d")) { debug = 1; }
      else if (!strcmp(argv[i], "-r")) { infile = 1; ia = i + 1; }
      else if (!strcmp(argv[i], "-w")) { outfile = 1; oa = i + 1; }
      else if (!strcmp(argv[i], "-s")) { stackfile = 1; sa = i + 1; }
      else if (!strcmp(argv[i], "-y")) { deldur = atoi(argv[++i]); }
      else if (!strcmp(argv[i], "-q")) { quiet = 1; }
      else if (!strcmp(argv[i], "-i")) { ignore_unsupported = 1; }
      else if (!strcmp(argv[i], "-=")) { use_b97directives = 1; }
      else if (!strcmp(argv[i], "-l")) { wrap_long_program_lines = 1; }
      else if (!strcmp(argv[i], "-t")) { inconsistent_trampoline = 1; }
      else
      {
        printf("Unknown option: %s\n", argv[i]);
        usage();
      }
    }
  }
  if (!quiet)
  {
    printf ("Befunge-93 Interpreter/Debugger v2.24\n");
  }

  memset(pg, ' ', LINEWIDTH * PAGEHEIGHT);

  strcpy(filename, argv[argc - 1]);
  if (strchr(filename, '.') == NULL)
  {
    strcat(filename, ".bf");
  }

  if ((f = fopen (filename, "r")) != NULL)             /*** Input Phase */
  {
    int x = 0, y = 0;
    char dc = '=', tc = ' ';
    int tt = 0; char s[80];
    int accept_pound = 1;

    while (!feof (f))
    {
      tc = fgetc (f);
      if (feof (f))
        break;
      if (use_b97directives && (x == 0) &&
          ((tc == dc) || (accept_pound && (tc == '#'))))
      {
        if (tc != '#') accept_pound = 0;
        tc = fgetc (f);
        if (tc == 'l')
        {
          while (tc != ' ')
          {
            tc = fgetc (f);
          }
          while (tc != '\n')
          {
            tc = fgetc (f);
            if (tc != '\n') { s[tt++] = tc; s[tt] = (char)0; }
          }
          if (strcmp(s, "b93"))
          {
            fprintf(stderr, "Error: only Befunge-93 (not %s) sources are supported by bef.\n", s);
            exit(10);
          }
        }
        while (tc != '\n')
        {
          tc = fgetc (f);
        }
      } else
      {
        accept_pound = 0;
        if (tc == '\n')
        {
          x = 0;
          y++;
          if (y >= PAGEHEIGHT) break;
        } else
        {
          cur = tc;
          x++;
          if (x >= LINEWIDTH)
          {
            if (!wrap_long_program_lines)
            {
              while (tc != '\n')
              {
                tc = fgetc (f);
                if (feof(f)) { y = PAGEHEIGHT; break; }
              }
            }
            x = 0;
            y++;
            if (y >= PAGEHEIGHT) break;
          }
        }
      }
    }
    fclose (f);
  } else
  {
    printf ("Error: couldn't open '%s' for input.\n", filename);
    exit (0);
  }

  if (infile)
  {
    if (!(fi = fopen (argv[ia], "r")))
    {
      printf ("Error : couldn't open '%s' for input.\n", argv[ia]);
      exit (0);
    }
  }

  if (outfile)
  {
    if (!(fo = fopen (argv[oa], "w")))
    {
      printf ("Error : couldn't open '%s' for output.\n", argv[oa]);
      exit (0);
    }
  }

  if (stackfile)
  {
    if (!(fs = fopen (argv[sa], "w")))
    {
      printf ("Error : couldn't open '%s' for output.\n", argv[sa]);
      exit (0);
    }
  }

  if (debug)
  {

#ifdef CONSOLE
    clrscr();
#  ifdef CURSORSHAPE
    _setcursortype(_NOCURSOR);
#  endif /* CURSORSHAPE */
#else
    printf ("%c[1;1H", 27);
    printf ("%c[2J", 27);
#endif /* CONSOLE */

    for(y = 0; y < SCREENHEIGHT; y++)
    {
      for(x = 0; x < SCREENWIDTH; x++)
      {
        if (isprint((int)cur))
        {
          printf("%c", cur);
        }
      }
      printf("\n");
    }

    x = y = 0;

#ifdef CUSRORSHAPE
    _setcursortype(_SOLIDCURSOR);
#endif /* CUSRORSHAPE */

  }

  while ((cur != '@') || (stringmode))          /*** Intepreting Phase */
  {
    if (debug)
    {
      if ((y < SCREENHEIGHT) && (x < SCREENWIDTH))
      {
#ifdef CONSOLE
        gotoxy(x+1, y+1);
        if (kbhit())
        {
          char c;
          /* ideally, pop up a debugging tool. for now, exit. */
          c = getch();
          if (c == 0)
          {
            c = getch();
          } else
          {
            if (c == 27)
            {
              /* pause */
              c = getch();
              if (c == 0)
              {
                c = getch();
              } else
              {
                if (c == 27)
                {
                  goto the_end;
                }
              }
            }
          }
        }
#else
        printf ("%c[%d;%dH", 27, y+1, x+1);
        fflush (stdout);
#endif /* CONSOLE */
      }
      befsleep (deldur);
    }
    if (stringmode && (cur != '"'))
      push (cur);
      else if (isdigit ((int)cur))
        push (cur - '0');
      else
        switch (cur)
        {
           case '>':            /* PC Right */
             dx = 1;
             dy = 0;
             break;
           case '<':            /* PC Left */
             dx = -1;
             dy = 0;
             break;
           case '^':            /* PC Up */
             dx = 0;
             dy = -1;
             break;
           case 'v':            /* PC Down */
             dx = 0;
             dy = 1;
             break;
           case '|':            /* Vertical 'If' */
             dx = 0;
             if (pop ())
               dy = -1;
             else
               dy = 1;
             break;
           case '_':            /* Horizontal 'If' */
             dy = 0;
             if (pop ())
               dx = -1;
             else
               dx = 1;
             break;
           case '+':            /* Add */
             push (pop () + pop ());
             break;
           case '-':            /* Subtract */
             {
               long a = pop();
               long b = pop();
               push(b - a);
             }
             break;
           case '*':            /* Multiply */
             push (pop () * pop ());
             break;
           case '/':            /* Integer Divide */
             {
               signed long a = pop ();
               signed long b = pop ();
               if (a == 0)
               {
                 if (!outfile)
                 {
                   printf("What do you want %ld/0 to be? ", b);
                 } else
                 {
                   fprintf(fo, "What do you want %ld/0 to be? ", b);
                 }
                 if (infile)
                 {
                   fscanf (fi, "%ld", &b);
                   push (b);
                 } else
                 {
                   if (!debug)
                   {
                     fscanf (stdin, "%ld", &b);
                     push (b);
                   }
                 }
               } else
               {
                 push (b / a);
               }
             }
             break;
           case '%':            /* Modulo */
             {
               signed long a = pop ();
               signed long b = pop ();
               push (b % a);
             }
             break;
           case '\\':           /* Swap */
             {
               signed long a = pop ();
               signed long b = pop ();
               push (a);
               push (b);
             }
             break;
           case '.':            /* Pop Out Integer */
             {
               if (outfile)
               {
                 fprintf (fo, "%ld ", pop ());
                 fflush (fo);
               } else
               {
                 if (!debug)
                 {
                   fprintf (stdout, "%ld ", pop ());
                   fflush (stdout);
                 } else
                 {
#ifdef CONSOLE
                   int x, y;
                   char s[172], t[172];
                   x = wherex();
                   y = wherey();
                   sprintf(s, "%ld ", pop());
                   gettext(1+strlen(s), DEBUGROW, 80, DEBUGROW, t);
                   puttext(1, DEBUGROW, 80-strlen(s), DEBUGROW, t);
                   gotoxy(81-strlen(s), DEBUGROW);
                   cputs(s);
                   gotoxy(x, y);
#endif /* CONSOLE */
                 }
               }
             }
             break;
           case ',':            /* Pop Out ASCII */
             {
               if (outfile)
               {
                 fprintf (fo, "%c", (char)pop ());
                 fflush (fo);
               } else
               {
                 if (!debug)
                 {
                   fprintf (stdout, "%c", (char)pop ());
                   fflush (stdout);
                 } else
                 {
#ifdef CONSOLE
                   int x, y;
                   long int p = pop();
                   char t[172];
                   x = wherex();
                   y = wherey();
                   gettext(2, DEBUGROW, 80, DEBUGROW, t);
                   puttext(1, DEBUGROW, 79, DEBUGROW, t);
                   gotoxy(80, DEBUGROW);
                   if ((p >= 32) && (p <= 255))
                   {
                     putch((int)p);
                   } else
                   {
                     if (p == 10)
                     {
                       putch(179);
                     } else
                     {
                       putch(168);
                     }
                   }
                   gotoxy(x, y);
#endif /* CONSOLE */
                 }
               }
             }
             break;
           case '"':            /* Toggle String Mode */
             stringmode = !stringmode;
             break;
           case ':':            /* Duplicate */
             {
               signed long a = pop ();
               push (a);
               push (a);
             }
             break;
           case '!':            /* Negate */
          if (pop())
            push(0);
          else
            push(1);
             break;
           case '`':
             {
               signed long b = pop ();
               signed long a = pop ();
               push (a > b);
             }
             break;
           case '#':            /* Bridge */
             x += dx;
             y += dy;
             break;
           case '$':            /* Pop and Discard */
             pop ();
             break;
           case '?':            /* Random Redirect */
             switch ((rand () / 32) % 4)
                {
                case 0:
                  dx = 1;
                  dy = 0;
                  break;
                case 1:
                  dx = -1;
                  dy = 0;
                  break;
                case 2:
                  dx = 0;
                  dy = -1;
                  break;
                case 3:
                  dx = 0;
                  dy = 1;
                  break;
                }
             break;
           case '&':            /* Input Integer */
             {
               signed long b;
               if (!undef_input_int) {
                 b = -1;
               }
               if (infile)
               {
                 fscanf (fi, "%ld", &b);
                 push (b);
               } else
               {
                 if (!debug)
                 {
                   fscanf (stdin, "%ld", &b);
                   push (b);
                 } else
                 {
#ifdef CONSOLE
                   int x, y;
                   long int p;
                   char t[172];
                   if (!undef_input_int) {
                     p = -1;
                   }
                   x = wherex();
                   y = wherey();
                   gettext(10, DEBUGROW, 80, DEBUGROW, t);
                   puttext(1, DEBUGROW, 71, DEBUGROW, t);
                   gotoxy(72, DEBUGROW);
                   clreol();
                   cscanf("%ld", &p);
                   push(p);
                   gotoxy(x, y);
#endif /* CONSOLE */
                 }
               }
             }
             break;
           case '~':            /* Input ASCII */
             {
               char c;
               if (infile)
               {
                 c = fgetc (fi);
                 push (c);
               } else
               {
                 if (!debug)
                 {
                   c = fgetc (stdin);
                   push (c);
                 } else
                 {
#ifdef CONSOLE
                   int x, y;
                   long int p;
                   char t[172];
                   x = wherex();
                   y = wherey();
                   gettext(2, DEBUGROW, 80, DEBUGROW, t);
                   puttext(1, DEBUGROW, 79, DEBUGROW, t);
                   gotoxy(80, DEBUGROW);
                   clreol();
                   p = getche();
                   if (p == '\r')
                   {
                     p = '\n';
                     gotoxy(80, DEBUGROW);
                     putch(179);
                   }
                   push(p);
                   gotoxy(x, y);
#endif /* CONSOLE */
                 }
               }
             }
             break;
           case 'g':            /* Get Value */
             {
               signed long y = pop (), x = pop ();
               if ((y < PAGEHEIGHT) && (y >= 0) && (x < LINEWIDTH) && (x >= 0))
               {
                 push (cur);
               } else
               {
                 if (!debug)
                 {
                   if (!quiet)
                   {
                     fprintf(stderr, "g 'Get' instruction out of bounds (%ld,%ld)\n", x, y);
                   }
                 }
                 push (0);
               }
             }
             break;
           case 'p':            /* Put Value */
             {
               signed long y = pop (), x = pop ();
               if ((y < PAGEHEIGHT) && (y >= 0) && (x < LINEWIDTH) && (x >= 0))
               {
                 cur = pop ();
               } else
               {
                 if (!debug)
                 {
                   if (!quiet)
                   {
                     fprintf(stderr, "p 'Put' instruction out of bounds (%ld,%ld)\n", x, y);
                   }
                 }
                 pop();
               }
               if ((debug) && (y < SCREENHEIGHT) && (x < SCREENWIDTH))
               {
#ifdef CONSOLE
                 gotoxy(x+1,y+1);
#else
                 printf ("%c[%d;%dH", 27, (int)(y+1), (int)(x+1));
#endif /* CONSOLE */
                 if (isprint ((int)cur)) printf ("%c", cur); else printf(".");
               }
             }
             break;
           case ' ':
             break;
           default:
             if ((!debug) && (!ignore_unsupported) && (!quiet))
             {
               fprintf(stderr, "Unsupported instruction '%c' (0x%02x) (maybe not Befunge-93?)\n", cur, cur);
             }
             break;
        }
      x += dx;
      y += dy;
      if (x < 0)
        if (v10err_compat)
        {
          x = LINEWIDTH;
        } else if (inconsistent_trampoline)
        {
          x = LINEWIDTH - 1;
        } else
        {
          x += LINEWIDTH;
        }
      else
        x = x % LINEWIDTH;
      if (y < 0)
        if (v10err_compat)
        {
          y = PAGEHEIGHT;
        } else if (inconsistent_trampoline)
        {
          y = PAGEHEIGHT - 1;
        } else
        {
          y += PAGEHEIGHT;
        }
      else
        y = y % PAGEHEIGHT;
      if (stackfile)
      {
        struct stack *s;
        for (s = head; s; s = s->next)
          fprintf(fs, "%ld ", s->val);
        fprintf(fs, "\n");
        fflush(fs);
      }
    }

#ifdef CONSOLE
the_end:
#endif /* CONSOLE */

  while (head != NULL) { pop(); }
  if (fi != NULL) fclose (fi);
  if (fo != NULL) fclose (fo);
  if (fs != NULL) fclose (fs);

  if (debug)
  {
#ifdef CONSOLE
#  ifdef CURSORSHAPE
    _setcursortype(_NORMALCURSOR);
#  endif /* CURSORSHAPE */
    gotoxy(1,22);
#else
    printf ("%c[22;1H", 27);
#endif /* CONSOLE */
  }

  exit (0);
  return 0;
}

/*
 * sleep for the given number of milliseconds, so far as we are able
 */
void befsleep (dur)
    int dur;
{
#if MSDOS
      delay (dur);
#else
  #ifdef _POSIX_C_SOURCE
        struct timespec tv;

        tv.tv_sec = dur / 1000;
        tv.tv_nsec = (dur % 1000) * 1000000;

        nanosleep(&tv, NULL);
  #else
        sleep (dur / 1000);
  #endif
#endif
}

/*
 * pushes a value onto the stack.
 */
void push (val)
    signed long val;
{
  struct stack *s;
  s = (struct stack *) malloc (sizeof (struct stack));
  s->val = val;
  s->next = head;
  head = s;
}

/*
 * pops a value off the stack. returns 0 in case of underflow.
 */
signed long pop ()
{
  signed long v;
  struct stack *s = head;
  if (s)
  {
    v = head->val;
    head = head->next;
    free (s);
    return v;
  } else
  {
    return 0;
  }
}

void usage ()
{
  printf ("USAGE: bef [-d] [-o] [-u] [-q] [-i] [-=] [-l] [-t]\n");
  printf ("           [-r input] [-w output] [-s stack] [-y delay] foo.bf\n");
  exit (1);
}