-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBAS-INT.c
1942 lines (1724 loc) · 44.6 KB
/
BAS-INT.c
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
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// CANBAS
// A tiny BASIC interpreter for scripting with the PCAN-Basic API
//
// Version 1.0.x
// Autor U.Wilhelm
//
// Based on the C-Interpreter from H.Schildt
// The program was originally published in Dr. Dobb's Journal in August, 1989 entitled "Building your own C interpreter"
// http://www.drdobbs.com/cpp/building-your-own-c-interpreter/184408184
//
// New features:
// change syntax to run Basic Keywords, use console features like goto xy, set color etc.
// add Remarks, add CAN Handling, use Windows Messages, add Wait and RND numbers,
// use a Staus Line etc.
//
// This is Software is at is. Use it or change it for your need...
// I will not do any support - debug it and optimize it
//
// PCAN is a registered Trademark of PEAK-System Technik GmbH
// The used Sofwtware API for CAN is part of the PEAK-System Software API PCANBasic.
// The C Header Files and the Documentation could be download from www.peak-system.com
// Every PEAK-System CAN Interface have a license to use the Interface DLL (pcanbasic.dll)
// The DLLs (32 and/or 64Bit) are not part of my packages.
// If you own a PEAK-System CAN Interface you also own a license of the API.
//
#include "stdio.h"
#include "setjmp.h"
#include "math.h"
#include "ctype.h"
#include "stdlib.h"
#include <windows.h>
#include <Wincon.h>
#include "tools.h"
#include "pcanbasic.h"
#define true 1
#define false 0
// #define CANSIMU
// Params of basic machine
#define NUM_LAB 100
#define LAB_LEN 20
#define FOR_NEST 100
#define SUB_NEST 100
#define PROG_SIZE 200000
#define TABLEN 8
#define DELIMITER 1
#define VARIABLE 2
#define NUMBER 3
#define COMMAND 4
#define STRING 5
#define QUOTE 6
#define REMARK 7
// tokens
#define PRINT 1
#define INPUT 2
#define IF 3
#define THEN 4
#define FOR 5
#define NEXT 6
#define TO 7
#define GOTO 8
#define EOL 9
#define FINISHED 10
#define GOSUB 11
#define RETURN 12
#define END 13
#define WAIT 14
#define MESSAGEBOX 15
#define CAN_RESET 16
#define CAN_GETSTATUS 17
#define CAN_WRITE 18
#define CAN_READ 19
#define CAN_FILTERMESSAGES 20
#define CAN_GETVALUE 21
#define CAN_SETVALUE 22
#define CAN_GETERRORTEXT 23
#define CAN_CLEARQUEUE 24
#define GOTOXY 25
#define SETCOLOR 26
#define CLRSCRN 27
#define RANDOM 28
#define CAN_WAITID 29
#define STATUSLINE 30
#define TICKCOUNT 31
// name of CANN DLL to load
char g_LibFileName[] = "PCANBasic";
// StdOut Handler
HANDLE g_hStdOut;
//Console Buffer Info
CONSOLE_SCREEN_BUFFER_INFO g_CSB_Info;
//Coord of Status Line
COORD g_coordStatus;
DWORD StatusCounter,StartStatusCounter;
BOOL g_statusline=false;
/*
typedef struct _CONSOLE_SCREEN_BUFFER_INFO {
COORD dwSize;
COORD dwCursorPosition;
WORD wAttributes;
SMALL_RECT srWindow;
COORD dwMaximumWindowSize;
} CONSOLE_SCREEN_BUFFER_INFO;
*/
// Pointer to code
char *prog; /* holds expression to be analyzed */
jmp_buf e_buf; /* hold environment for longjmp() */
// Store our 26 VARs
long variables[26]= { /* 26 user variables, A-Z */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0
};
// The keyword lookup table
struct commands {
char command[20];
char tok;
} table[] = { /* Commands must be entered lowercase in this table. */
"print", PRINT,
"input", INPUT,
"if", IF,
"then", THEN,
"goto", GOTO,
"for", FOR,
"next", NEXT,
"to", TO,
"gosub", GOSUB,
"return", RETURN,
"end", END,
"wait", WAIT,
"messagebox", MESSAGEBOX,
"can_reset", CAN_RESET,
"can_getstatus",CAN_GETSTATUS,
"can_write", CAN_WRITE,
"can_read", CAN_READ,
"can_filtermessages",CAN_FILTERMESSAGES,
"can_getvalue", CAN_GETVALUE,
"can_setvalue",CAN_SETVALUE,
"can_geterrortext",CAN_GETERRORTEXT,
"can_waitid",CAN_WAITID,
"can_clearqueue",CAN_CLEARQUEUE,
"gotoxy",GOTOXY,
"setcolor",SETCOLOR,
"clrscrn",CLRSCRN,
"random",RANDOM,
"statusline", STATUSLINE,
"tickcount", TICKCOUNT,
"", END /* mark end of table */
};
// Token
char token[80];
char token_type,tok;
// a LABLE storing struct
struct label {
char name[LAB_LEN];
char *p; /* points to place to go in source file*/
};
// Label Table
struct label label_table[NUM_LAB];
// The STACK
struct for_stack {
int var; /* counter variable */
long target; /* target value */
char *loc;
} fstack[FOR_NEST]; /* stack for FOR/NEXT loop */
struct for_stack fpop();
char *gstack[SUB_NEST]; /* stack for gosub */
int ftos; /* index to top of FOR stack */
int gtos; /* index to top of GOSUB stack */
int global_break=false;
BOOL g_CANSIMU=false;
// Extern Functions - from Tools.c
extern BOOL LoadDLL();
extern BOOL UnloadDLL();
extern int GetFunctionAdress(HINSTANCE h_module);
extern long htoi(char s[]);
extern print_howto(),print_help(),print_help_devicetype(),print_help_baudrate();
extern print_help_hwtype(),print_help_ioport(),print_help_int(),print_help_syntax();
// Intern Function
void print(), scan_labels(), find_eol(), exec_goto();
void exec_if(), exec_for(), next(), fpush(), input();
void gosub(), greturn(), gpush(), label_init();
void serror(), get_exp(), putback();
void level2(), level3(), level4(), level5(), level6(), primitive();
void unary(), arith(), wait(), basic_messagebox();
char *find_label(), *gpop();
void assignment(),gotoxy(),setcolor(),clrscrn(),random(),can_waitid(), tickcount();
void can_reset(),can_getstatus(),can_write(),can_read(),can_setvalue(),can_getvalue(),can_geterrortext(),can_filtermessages(),can_clearqueue(),statusline();
int iswhite(),isdelim(),look_up(),find_var();
unsigned long load_program(char *p,char *fname);
int CheckParams(char *devicehandle, char *baudrate, char *hwtype, char *ioport, char *interrupt);
int ConsoleHandler(DWORD CEvent);
// The Main....
main(argc, argv)
int argc;
char *argv[];
{
char version[20]= "1.0.1";
char buffer[255];
DWORD myTickCounter,StartTickCounter;
char *p_buf;
char *t;
unsigned long filesize;
int i, ret;
if(SetConsoleCtrlHandler( (PHANDLER_ROUTINE)ConsoleHandler,TRUE)==FALSE) { // unable to install handler...display message to the user
printf("CANBas -> Unable to install Ctrl-Handler!\n");
return -1; }
SetConsoleTitle("CANBAS");
g_hStdOut=GetStdHandle(STD_OUTPUT_HANDLE );
g_coordStatus.X=0;
g_coordStatus.Y=24;
//Handle all the basic stuff to be sure that the command line paramaters are OK
printf("CANBas - a simple CAN scripting language\n");
printf("using the PCAN-Basic Interface DLL for PEAK-System CAN Adapters.\n");
printf("PCAN is a registered Trademark of PEAK-System GmbH.\n");
#ifndef X64
printf("32Bit Version: %s \n",version);
#else
printf("64Bit Version: %s \n",version);
#endif
if(argc<2) {
print_howto();
exit(1);
}
if(!stricmp(argv[1],"HELP"))
{
if(argv[2]==NULL)
print_help();
else
if(!stricmp(argv[2],"DEVICETYPE"))
print_help_devicetype();
else
if(!stricmp(argv[2],"BAUDRATE"))
print_help_baudrate();
else
if(!stricmp(argv[2],"HWTYPE"))
print_help_hwtype();
else
if(!stricmp(argv[2],"IOPORT"))
print_help_ioport();
else
if(!stricmp(argv[2],"INT"))
print_help_int();
else
print_howto();
exit(1);
}
else{
if(!stricmp(toupper(argv[1]),"SYNTAX"))
{
print_help_syntax();
exit(1);
}
else{
if(!stricmp(toupper(argv[1]),"SAMPLE"))
{
printf("Sample:\nuse basic file TestECU.bas with a USB Adapter Channel 1 running with 500k\n");
printf("\nCANBas TestECU.bas 0x51 0x001c\n");
exit(1);
}
}
}
// Check if DeviceType and Baudrate are valid PCANBasic Parametes
// For that we need to see if the Arguments counter is >3
if(argc<4)
{
if(argc==3 && !stricmp(argv[2],"SIMU"))
{
printf("Run ins SIMU mode - ignore CAN");
g_CANSIMU=true;
}
else
{
printf("missing arguments...\n");
print_howto();
exit(1);
}
}
else
{
if(!CheckParams(argv[2], argv[3],argv[4], argv[5], argv[6]))
exit(1);
}
// Allocate the memory for the program
if(!(p_buf=(char *) malloc(PROG_SIZE+1))) {
printf("allocation failure - out of memory!\n");
exit(1);
}
// Set Console Windows Name to the loaded program file
sprintf(buffer,"CANBas running: %s",argv[1]);
SetConsoleTitle(buffer);
// load the program to execute...
filesize=load_program(p_buf,argv[1]);
if(filesize<=0) exit(1);
p_buf[filesize]='\0';
// used for check the "real" programm code after remove the REM (#)
// printf("%s\n",p_buf);
if(setjmp(e_buf)) exit(1); /* initialize the long jump buffer */
prog = p_buf;
scan_labels(); /* find the labels in the program */
ftos = 0; /* initialize the FOR stack index */
gtos = 0; /* initialize the GOSUB stack index */
if(!g_CANSIMU)
{
if(!LoadDLL())
exit(1);
#ifndef CANSIMU
CANStatus = g_CAN_Initialize(CANChannel, CANBaudrate, CANHwType, CANIOPort, CANInterrupt);
// If CANSatatus is OK, we could use the CAN Cahnnel CANChannel for all other functions...
if(CANStatus!=PCAN_ERROR_OK)
{
printf("Error while initialize CAN Interface: %d\n", CANStatus);
exit(1);
}
#endif
}
// Hole Startzeit
#ifdef _DEBUG
StartTickCounter=GetTickCount();
#endif
StartStatusCounter=0;
// Here we start...
do {
//Here we update the status line
if(g_statusline)
{
StatusCounter=GetTickCount();
if(StatusCounter-StartStatusCounter>1000)
{
//Get the actually Info of Cursor
GetConsoleScreenBufferInfo(g_hStdOut,&g_CSB_Info);
SetConsoleTextAttribute(g_hStdOut,FOREGROUND_INTENSITY | FOREGROUND_GREEN);
SetConsoleCursorPosition(g_hStdOut,g_coordStatus);
if(!g_CANSIMU)
{
ret = g_CAN_GetStatus(CANChannel);
g_CAN_GetErrorText(ret,0x00,buffer);
printf("used CAN Ch. 0x%02x, BTR0/BTR1: 0x%04x State: %s\tUpdate:%u",CANChannel, CANBaudrate,buffer, StatusCounter);
}else
printf("used CAN Ch. SIMU, BTR0/BTR1: SIMU State: SIMU\tUpdate:%u", StatusCounter);
SetConsoleCursorPosition(g_hStdOut,g_CSB_Info.dwCursorPosition);
SetConsoleTextAttribute(g_hStdOut,g_CSB_Info.wAttributes);
StartStatusCounter=GetTickCount();
}
}
token_type = get_token();
/* check for assignment statement */
if(token_type==VARIABLE) {
putback(); /* return the var to the input stream */
assignment(); /* must be assignment statement */
}
else /* is command */
{
switch(tok) {
case PRINT:
print();
break;
case GOTO:
exec_goto();
break;
case IF:
exec_if();
break;
case FOR:
exec_for();
break;
case NEXT:
next();
break;
case INPUT:
input();
break;
case GOSUB:
gosub();
break;
case RETURN:
greturn();
break;
case WAIT:
wait();
break;
case MESSAGEBOX:
basic_messagebox();
break;
case CAN_RESET:
can_reset();
break;
case CAN_GETSTATUS:
can_getstatus();
break;
case CAN_WRITE:
can_write();
break;
case CAN_READ:
can_read();
break;
case CAN_FILTERMESSAGES:
can_filtermessages();
break;
case CAN_GETVALUE:
can_getvalue();
break;
case CAN_SETVALUE:
can_setvalue();
break;
case CAN_GETERRORTEXT:
can_geterrortext();
break;
case CAN_WAITID:
can_waitid();
break;
case CAN_CLEARQUEUE:
can_clearqueue();
break;
case GOTOXY:
gotoxy();
break;
case SETCOLOR:
setcolor();
break;
case CLRSCRN:
clrscrn();
break;
case RANDOM:
random();
break;
case STATUSLINE:
statusline();
break;
case TICKCOUNT:
tickcount();
break;
case END:
tok = FINISHED;
}
}
} while (tok != FINISHED && global_break!=true);
//End of Programm...
#ifdef _DEBUG
myTickCounter=GetTickCount();
printf("used ticks: %d\n", myTickCounter-StartTickCounter);
#endif
if(!g_CANSIMU)
{
#ifndef CANSIMU
g_CAN_Uninitialize(CANChannel);
#endif
UnloadDLL();
}
exit;
}
// Load a program to buffer - OLD VERSION
/*
unsigned long load_program_old(char *p,char *fname)
{
FILE *fp;
char temp_c;
unsigned long i=0;
// Open File
if(!(fp=fopen(fname, "rb"))) return 0;
i = 0;
do{
temp_c=getc(fp);
*p = temp_c; // copy to prog buffer
p++; i++; // increment prog buffer pointer and size counter
}while(!feof(fp) && i<PROG_SIZE); // until End of File or Buffer reached
i--; // to return right size...
fclose(fp); // close file
return i; //return real size in Bytes
}
*/
// Load file to buffer - remove the # lines
unsigned long load_program(char *p,char *fname)
{
FILE *fp;
char temp_c;
unsigned long filesize=0;
int j,i;
char LineBuffer[512];
// Open File
if(!(fp=fopen(fname, "rb"))) return 0;
j,i = 0;
// remove REM Lines (#)
// and read the rest into buffer
do{
//read ONE single line
i=0;
do{
temp_c=getc(fp);
LineBuffer[i++]=temp_c;
}while(!feof(fp) && (temp_c!=0x0a) );
// if(!feof(fp) && i>0) // not end of file?
if(i>0) // not end of file?
{
LineBuffer[i]='\0'; // add a String delimiter at the end of the line
// Here we have a single Line in LineBuffer
for(j=0;j<strlen(LineBuffer);j++)
{
if(LineBuffer[j]==' ' || LineBuffer[j]=='\t' || LineBuffer[j]==0x0a || LineBuffer[j]==0x0d)
j++;
else
{
if(LineBuffer[j]=='#')
{
//Start of REM Block
//LineBuffer[0]='\0';
break;
}else //any other Char - > it´s code
{
// break;
//Now we have one line in the buffer
memcpy(p,LineBuffer,strlen(LineBuffer));
// printf("%s",LineBuffer);
p=p+strlen(LineBuffer); // copy this line to the gloabl programm buffer
filesize=filesize+strlen(LineBuffer); //add the size of the added line to the char counter of the gloabl programm buffer
break;
}
}
}
/*
//Now we have one line in the buffer
memcpy(p,LineBuffer,strlen(LineBuffer));
// printf("%s",LineBuffer);
p=p+strlen(LineBuffer); // copy this line to the gloabl programm buffer
filesize=filesize+strlen(LineBuffer); //add the size of the added line to the char counter of the gloabl programm buffer
i=0;// reset i to zero - new line
*/
}
}while(!feof(fp) && i<PROG_SIZE); // until End of File or Buffer reached
fclose(fp); // close file
return filesize-1; //return real size in Bytes
}
/* Assign a variable a value. */
void assignment()
{
long var, value;
/* get the variable name */
get_token();
if(!isalpha(*token)) {
serror(4);
return;
}
var = toupper(*token)-'A';
/* get the equals sign */
get_token();
if(*token!='=') {
serror(3);
return;
}
/* get the value to assign to var */
get_exp(&value);
/* assign the value */
variables[var] = value;
}
/* wait for xx ms */
void wait()
{
long answer;
get_token(); /* get next list item */
if(tok==EOL || tok==FINISHED)
serror(0);
if(token_type==QUOTE) /* is string */
serror(0);
else { /* is expression */
putback();
get_exp(&answer);
get_token();
Sleep(answer);
}
if(tok!=EOL && tok!=FINISHED) serror(0);
}
/* Execute a simple version of the BASIC PRINT statement */
void print()
{
long answer;
int len=0, spaces;
char last_delim;
do {
get_token(); /* get next list item */
if(tok==EOL || tok==FINISHED) break;
if(token_type==QUOTE) { /* is string */
printf(token);
len += strlen(token);
get_token();
}
else { /* is expression */
putback();
get_exp(&answer);
get_token();
len += printf("%d", answer);
}
last_delim = *token;
if(*token==';') {
/* compute number of spaces to move to next tab */
spaces = TABLEN - (len % TABLEN);
len += spaces; /* add in the tabbing position */
while(spaces) {
printf(" ");
spaces--;
}
}
else if(*token==',') /* do nothing */;
else if(tok!=EOL && tok!=FINISHED) serror(0);
} while (*token==';' || *token==',');
if(tok==EOL || tok==FINISHED) {
if(last_delim != ';' && last_delim!=',') printf("\n");
}
else serror(0); /* error is not , or ; */
}
/* Execute a simple version of the BASIC PRINT statement */
void basic_messagebox()
{
long answer;
int len=0, spaces;
char last_delim;
char printbuffer[1024];
char buffer[255];
sprintf(printbuffer,"");
do {
get_token(); /* get next list item */
if(tok==EOL || tok==FINISHED) break;
if(token_type==QUOTE) { /* is string */
strcat(printbuffer,token);
len += strlen(token);
get_token();
}
else { /* is expression */
putback();
get_exp(&answer);
get_token();
len += sprintf(buffer,"%d", answer);
strcat(printbuffer, buffer);
}
last_delim = *token;
if(*token==';') {
/* compute number of spaces to move to next tab */
spaces = 8 - (len % 8);
len += spaces; /* add in the tabbing position */
while(spaces) {
strcat(printbuffer," ");
spaces--;
}
}
else if(*token==',') /* do nothing */;
else if(tok!=EOL && tok!=FINISHED) serror(0);
} while (*token==';' || *token==',');
if(tok==EOL || tok==FINISHED) {
if(last_delim != ';' && last_delim!=',') strcat(printbuffer,"\n");
}
else serror(0); /* error is not , or ; */
MessageBox(NULL,printbuffer, "CANBAS Info", MB_ICONINFORMATION);
}
/* Find all labels. */
void scan_labels()
{
int addr;
char *temp;
label_init(); /* zero all labels */
temp = prog; /* save pointer to top of program */
/* if the first token in the file is a label */
get_token();
if(token_type==NUMBER) {
strcpy(label_table[0].name,token);
label_table[0].p=prog;
}
find_eol();
do {
get_token();
if(token_type==NUMBER) {
addr = get_next_label(token);
if(addr==-1 || addr==-2) {
(addr==-1) ?serror(5):serror(6);
}
strcpy(label_table[addr].name, token);
label_table[addr].p = prog; /* current point in program */
}
/* if not on a blank line, find next line */
if(tok!=EOL) find_eol();
} while(tok!=FINISHED);
prog = temp; /* restore to original */
}
/* Find the start of the next line. */
void find_eol()
{
while(*prog!='\n' && *prog!='\0') ++prog;
if(*prog) prog++;
}
/* Return index of next free position in label array.
A -1 is returned if the array is full.
A -2 is returned when duplicate label is found.
*/
get_next_label(s)
char *s;
{
register int t;
for(t=0;t<NUM_LAB;++t) {
if(label_table[t].name[0]==0) return t;
if(!strcmp(label_table[t].name,s)) return -2; /* dup */
}
return -1;
}
/* Find location of given label. A null is returned if
label is not found; otherwise a pointer to the position
of the label is returned.
*/
char *find_label(s)
char *s;
{
register int t;
for(t=0; t<NUM_LAB; ++t)
if(!strcmp(label_table[t].name,s)) return label_table[t].p;
return '\0'; /* error condition */
}
/* Execute a GOTO statement. */
void exec_goto()
{
char *loc;
get_token(); /* get label to go to */
/* find the location of the label */
loc = find_label(token);
if(loc=='\0')
serror(7); /* label not defined */
else prog=loc; /* start program running at that loc */
}
/* Initialize the array that holds the labels.
By convention, a null label name indicates that
array position is unused.
*/
void label_init()
{
register int t;
for(t=0; t<NUM_LAB; ++t) label_table[t].name[0]='\0';
}
/* Execute an IF statement. */
void exec_if()
{
int x , y, cond;
char op;
get_exp(&x); /* get left expression */
get_token(); /* get the operator */
if(!strchr("=<>", *token)) {
serror(0); /* not a legal operator */
return;
}
op=*token;
get_exp(&y); /* get right expression */
/* determine the outcome */
cond = 0;
switch(op) {
case '<':
if(x<y) cond=1;
break;
case '>':
if(x>y) cond=1;
break;
case '=':
if(x==y) cond=1;
break;
}
if(cond) { /* is true so process target of IF */
get_token();
if(tok!=THEN) {
serror(8);
return;
}/* else program execution starts on next line */
}
else find_eol(); /* find start of next line */
}
/* Execute a FOR loop. */
void exec_for()
{
struct for_stack i;
int value;
get_token(); /* read the control variable */
if(!isalpha(*token)) {
serror(4);
return;
}
i.var=toupper(*token)-'A'; /* save its index */
get_token(); /* read the equals sign */
if(*token!='=') {
serror(3);
return;
}
get_exp(&value); /* get initial value */
variables[i.var]=value;
get_token();
if(tok!=TO) serror(9); /* read and discard the TO */
get_exp(&i.target); /* get target value */
/* if loop can execute at least once, push info on stack */
if(value>=variables[i.var]) {
i.loc = prog;
fpush(i);
}
else /* otherwise, skip loop code altogether */
while(tok!=NEXT) get_token();
}
/* Execute a NEXT statement. */
void next()
{
struct for_stack i;
i = fpop(); /* read the loop info */
variables[i.var]++; /* increment control variable */
if(variables[i.var]>i.target) return; /* all done */
fpush(i); /* otherwise, restore the info */
prog = i.loc; /* loop */
}
/* Push function for the FOR stack. */
void fpush(i)
struct for_stack i;
{
if(ftos>FOR_NEST)
serror(10);
fstack[ftos]=i;
ftos++;
}
struct for_stack fpop()
{
ftos--;
if(ftos<0) serror(11);
return(fstack[ftos]);
}
/* Execute a simple form of the BASIC INPUT command */
void input()
{
char var;
long i;
get_token(); /* see if prompt string is present */
if(token_type==QUOTE) {
printf(token); /* if so, print it and check for comma */
get_token();
if(*token!=',') serror(1);
get_token();
}
else printf("? "); /* otherwise, prompt with / */
var = toupper(*token)-'A'; /* get the input var */
scanf("%d", &i); /* read input */
variables[var] = i; /* store it */
}
/* Execute a GOSUB command. */
void gosub()
{
char *loc;
get_token();
/* find the label to call */
loc = find_label(token);
if(loc=='\0')
serror(7); /* label not defined */
else {
gpush(prog); /* save place to return to */
prog = loc; /* start program running at that loc */
}
}
/* Return from GOSUB. */
void greturn()
{
prog = gpop();
}
/* GOSUB stack push function. */
void gpush(s)
char *s;
{
gtos++;