File: dbg.c

package info (click to toggle)
cc65 2.19-2
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 20,268 kB
  • sloc: ansic: 117,151; asm: 66,339; pascal: 4,248; makefile: 1,009; perl: 607
file content (1593 lines) | stat: -rw-r--r-- 36,612 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
/*
** dbg.c
**
** Ullrich von Bassewitz, 08.08.1998
**
*/



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
#include <ctype.h>
#include <6502.h>
#include <dbg.h>


/*****************************************************************************/
/*                             Function forwards                             */
/*****************************************************************************/



/* Forwards for handler functions */
static char AsmHandler (void);
static char RegHandler (void);
static char StackHandler (void);
static char CStackHandler (void);
static char DumpHandler (void);
static char HelpHandler (void);

/* Forwards for other functions */
static void DisplayPrompt (const char* s);
static void SingleStep (char StepInto);
static void RedrawStatic (char  Frame);
static void Redraw (char Frame);
static char GetKeyUpdate (void);



/*****************************************************************************/
/*                                   Data                                    */
/*****************************************************************************/



/* Color definitions */
#if defined(__C16__)
#  define COLOR_BORDER          (BCOLOR_DARKBLUE | CATTR_LUMA6)
#  define COLOR_BACKGROUND      COLOR_WHITE
#  define COLOR_TEXTHIGH        COLOR_BLACK
#  define COLOR_TEXTLOW         COLOR_GRAY1
#  define COLOR_FRAMEHIGH       COLOR_BLACK
#  define COLOR_FRAMELOW        COLOR_GRAY2
#else
#  if defined(COLOR_GRAY3)
#    define COLOR_BORDER        COLOR_BLACK
#    define COLOR_BACKGROUND    COLOR_BLACK
#    define COLOR_TEXTHIGH      COLOR_WHITE
#    define COLOR_TEXTLOW       COLOR_GRAY3
#    define COLOR_FRAMEHIGH     COLOR_WHITE
#    define COLOR_FRAMELOW      COLOR_GRAY3
#  else
#    if defined(__APPLE2__)
#      define COLOR_BORDER      COLOR_BLACK
#      define COLOR_BACKGROUND  COLOR_BLACK
#      define COLOR_TEXTHIGH    COLOR_BLACK
#      define COLOR_TEXTLOW     COLOR_BLACK
#      define COLOR_FRAMEHIGH   COLOR_BLACK
#      define COLOR_FRAMELOW    COLOR_BLACK
#    else
#      define COLOR_BORDER      COLOR_BLACK
#      define COLOR_BACKGROUND  COLOR_BLACK
#      define COLOR_TEXTHIGH    COLOR_WHITE
#      define COLOR_TEXTLOW     COLOR_WHITE
#      define COLOR_FRAMEHIGH   COLOR_WHITE
#      define COLOR_FRAMELOW    COLOR_WHITE
#    endif
#  endif
#endif
#ifndef COLOR_BLACK
#  define COLOR_BLACK   0
#endif
#ifndef COLOR_WHITE
#  define COLOR_WHITE   1
#endif

/* Screen definitions */
#if defined(__CBM610__)
#  define BIGSCREEN
#  define MAX_X         80
#  define MAX_Y         25
#  define DUMP_BYTES    16
#elif defined(__APPLE2__) || defined(__ATARI__)
#  define MAX_X         40
#  define MAX_Y         24
#  define DUMP_BYTES     8
#else
#  define MAX_X         40
#  define MAX_Y         25
#  define DUMP_BYTES     8
#endif

/* Replacement key definitions */
#ifndef CH_DEL
#  define CH_DEL        ('H' - 'A' + 1)         /* Ctrl+H */
#endif

/* Replacement char definitions */
#ifndef CH_ULCORNER
#  define CH_ULCORNER   '+'
#endif
#ifndef CH_URCORNER
#  define CH_URCORNER   '+'
#endif
#ifndef CH_LLCORNER
#  define CH_LLCORNER   '+'
#endif
#ifndef CH_LRCORNER
#  define CH_LRCORNER   '+'
#endif
#ifndef CH_TTEE
#  define CH_TTEE       '+'
#endif
#ifndef CH_LTEE
#  define CH_LTEE       '+'
#endif
#ifndef CH_RTEE
#  define CH_RTEE       '+'
#endif
#ifndef CH_BTEE
#  define CH_BTEE       '+'
#endif
#ifndef CH_CROSS
#  define CH_CROSS      '+'
#endif

/* Defines for opcodes */
#define OPC_BRK         0x00
#define OPC_BPL         0x10
#define OPC_JSR         0x20
#define OPC_BMI         0x30
#define OPC_RTI         0x40
#define OPC_JMP         0x4C
#define OPC_BVC         0x50
#define OPC_RTS         0x60
#define OPC_JMPIND      0x6C
#define OPC_BVS         0x70
#define OPC_BCC         0x90
#define OPC_BCS         0xB0
#define OPC_BNE         0xD0
#define OPC_BEQ         0xF0



/* Register values that are used also in the assembler stuff */
extern unsigned char DbgSP;             /* Stack pointer */
extern unsigned      DbgCS;             /* C stack pointer */
extern unsigned      DbgHI;             /* High 16 bit of primary reg */



/* Descriptor for one text line */
typedef struct {
    unsigned char x;
    unsigned char y;
    const char*   text;
} TextDesc;

/* Window descriptor */
typedef struct {
    unsigned char fd_tl;                /* Top left char */
    unsigned char fd_tr;                /* Top right char */
    unsigned char fd_bl;                /* Bottom left char */
    unsigned char fd_br;                /* Bottom right char */
    unsigned char fd_x1, fd_y1;         /* Upper left corner */
    unsigned char fd_x2, fd_y2;         /* Lower right corner */
    unsigned char fd_width, fd_height;  /* Redundant but faster */
    unsigned char fd_visible;           /* Is the window currently visible? */
    char (*fd_func) (void);             /* Handler function */
    unsigned char fd_textcount;         /* Number of text lines to print */
    const TextDesc* fd_text;            /* Static text in the window */
} FrameDesc;



/* Texts for the windows */
static const TextDesc RegText [] = {
    { 1,  0, "PC" },
    { 1,  1, "SR" },
    { 1,  2, "A"  },
    { 1,  3, "X"  },
    { 1,  4, "Y"  },
    { 1,  5, "SP" },
    { 1,  6, "CS" },
    { 1,  7, "HI" }
};
static const TextDesc HelpText [] = {
    { 1,  0, "F1, ?     Help"                           },
    { 1,  1, "F2, t     Toggle breakpoint"              },
    { 1,  2, "F3, u     Run until subroutine returns"   },
    { 1,  3, "F4, h     Run to cursor"                  },
    { 1,  4, "F7, space Step into"                      },
    { 1,  5, "F8, enter Step over"                      },
    { 1,  6, "1-5       Select active window"           },
    { 1,  7, "+         Page down"                      },
    { 1,  8, "-         Page up"                        },
    { 1,  9, "Cursor    Move up/down"                   },
    { 1, 10, "a/z       Move up/down"                   },
    { 1, 11, "c         Continue"                       },
    { 1, 12, "f         Follow instruction"             },
    { 1, 13, "o         Goto origin"                    },
    { 1, 14, "p         Use as new PC value"            },
    { 1, 15, "q         Quit"                           },
    { 1, 16, "r         Redraw screen"                  },
    { 1, 17, "s         Skip next instruction"          },
};


/* Window data */
static const FrameDesc AsmFrame = {
    CH_ULCORNER, CH_TTEE, CH_LTEE, CH_CROSS,
    0, 0, MAX_X - 10, 15,
    MAX_X - 11, 14,
    1,
    AsmHandler,
    0, 0
};
static const FrameDesc RegFrame = {
    CH_TTEE, CH_URCORNER, CH_LTEE, CH_RTEE,
    MAX_X - 10, 0, MAX_X - 1, 9,
    8, 8,
    1,
    RegHandler,
    sizeof (RegText) / sizeof (RegText [0]), RegText
};
static const FrameDesc StackFrame = {
    CH_LTEE, CH_RTEE, CH_CROSS, CH_RTEE,
    MAX_X - 10, 9, MAX_X - 1, 15,
    8, 5,
    1,
    StackHandler,
    0, 0
};
static const FrameDesc CStackFrame = {
    CH_CROSS, CH_RTEE, CH_BTEE, CH_LRCORNER,
    MAX_X - 10, 15, MAX_X - 1, MAX_Y - 1,
    8, MAX_Y - 17,
    1,
    CStackHandler,
    0, 0
};
static const FrameDesc DumpFrame = {
    CH_LTEE, CH_CROSS, CH_LLCORNER, CH_BTEE,
    0, 15, MAX_X - 10, MAX_Y-1,
    MAX_X - 11, MAX_Y - 17,
    1,
    DumpHandler,
    0, 0
};
static const FrameDesc HelpFrame = {
    CH_ULCORNER, CH_URCORNER, CH_LLCORNER, CH_LRCORNER,
    0, 0, MAX_X - 1, MAX_Y-1,
    MAX_X - 2, MAX_Y - 2,
    0,
    HelpHandler,
    sizeof (HelpText) / sizeof (HelpText [0]), HelpText
};
static const FrameDesc* const Frames [] = {
    &AsmFrame,
    &RegFrame,
    &StackFrame,
    &CStackFrame,
    &DumpFrame,
    &HelpFrame
};

/* Number of active frame, -1 = none */
static int ActiveFrame = -1;

/* Window names */
#define WIN_ASM         0
#define WIN_REG         1
#define WIN_STACK       2
#define WIN_CSTACK      3
#define WIN_DUMP        4
#define WIN_HELP        5

/* Other window data */
static unsigned AsmAddr;        /* Start address of output */
static unsigned DumpAddr;       /* Start address of output */
static unsigned CStackAddr;     /* Start address of output */
static unsigned char StackAddr; /* Start address of output */



/* Prompt line data */
static const char* ActivePrompt = 0;  /* Last prompt line displayed */
static char PromptColor;        /* Color behind prompt */
static char PromptLength;       /* Length of current prompt string */



/* Values for the bk_use field of struct BreakPoint */
#define BRK_EMPTY       0x00
#define BRK_USER        0x01
#define BRK_TMP         0x80

/* Structure describing a breakpoint */
typedef struct {
    unsigned      bk_addr;      /* Address, 0 if unused */
    unsigned char bk_opc;       /* Opcode */
    unsigned char bk_use;       /* 1 if in use, 0 otherwise */
} BreakPoint;



/* Temporary breakpoints - also accessed from the assembler source */
#define MAX_USERBREAKS  10
unsigned char DbgBreakCount = 0;
BreakPoint DbgBreaks [MAX_USERBREAKS+2];



/*****************************************************************************/
/*              Forwards for functions in the assembler source               */
/*****************************************************************************/



BreakPoint* DbgGetBreakSlot (void);
/* Search for a free breakpoint slot. Return a pointer to the slot or 0 */

BreakPoint* DbgIsBreak (unsigned Addr);
/* Check if there is a user breakpoint at the given address, if so, return
** a pointer to the slot, else return 0.
*/



/*****************************************************************************/
/*                         Frame/window drawing code                         */
/*****************************************************************************/



static void DrawFrame (register const FrameDesc* F, char Active)
/* Draw one window frame */
{
    const TextDesc* T;
    unsigned char Count;
    unsigned char tl, tr, bl, br;
    unsigned char x1, y1, width;
    unsigned char OldColor;

    /* Determine the characters for the corners, set frame color */
    if (Active) {
        OldColor = textcolor (COLOR_FRAMEHIGH);
        tl = CH_ULCORNER;
        tr = CH_URCORNER;
        bl = CH_LLCORNER;
        br = CH_LRCORNER;
    } else {
        OldColor = textcolor (COLOR_FRAMELOW);
        tl = F->fd_tl;
        tr = F->fd_tr;
        bl = F->fd_bl;
        br = F->fd_br;
    }

    /* Get the coordinates into locals for faster access */
    x1 = F->fd_x1;
    y1 = F->fd_y1;
    width = F->fd_width;

    /* Top line */
    cputcxy (x1, y1, tl);
    chline (width);
    cputc (tr);

    /* Left line */
    cvlinexy (x1, ++y1, F->fd_height);

    /* Bottom line */
    cputc (bl);
    chline (width);
    cputc (br);

    /* Right line */
    cvlinexy (F->fd_x2, y1, F->fd_height);

    /* If the window has static text associated, print the text */
    (void) textcolor (COLOR_TEXTLOW);
    Count = F->fd_textcount;
    T = F->fd_text;
    while (Count--) {
        cputsxy (x1 + T->x, y1 + T->y, T->text);
        ++T;
    }

    /* Set the old color */
    (void) textcolor (OldColor);
}



static void DrawFrames (void)
/* Draw all frames */
{
    unsigned char I;
    const FrameDesc* F;

    /* Build the frame layout of the screen */
    for (I = 0; I < sizeof (Frames) / sizeof (Frames [0]); ++I) {
        F = Frames [I];
        if (F->fd_visible) {
            DrawFrame (F, 0);
        }
    }
}



static void ActivateFrame (int Num, unsigned char Clear)
/* Activate a new frame, deactivate the old one */
{
    unsigned char y;
    register const FrameDesc* F;

    if (ActiveFrame != Num) {

        /* Deactivate the old one */
        if (ActiveFrame >= 0) {
            DrawFrame (Frames [ActiveFrame], 0);
        }

        /* Activate the new one */
        if ((ActiveFrame = Num) >= 0) {
            F = Frames [ActiveFrame];
            /* Clear the frame if requested */
            if (Clear) {
                for (y = F->fd_y1+1; y < F->fd_y2; ++y) {
                    cclearxy (F->fd_x1+1, y, F->fd_width);
                }
            }
            DrawFrame (F, 1);
        }

        /* Redraw the current prompt line */
        DisplayPrompt (ActivePrompt);

    }
}



/*****************************************************************************/
/*                                Prompt line                                */
/*****************************************************************************/



static void DisplayPrompt (const char* s)
/* Display a prompt */
{
    unsigned char OldColor;

    /* Remember the current color */
    OldColor = textcolor (COLOR_TEXTHIGH);

    /* Clear the old prompt if there is one */
    if (ActivePrompt) {
        (void) textcolor (PromptColor);
        chlinexy ((MAX_X - PromptLength) / 2, MAX_Y-1, PromptLength);
    }

    /* Get the new prompt data */
    ActivePrompt = s;
    PromptColor  = OldColor;
    PromptLength = strlen (ActivePrompt);

    /* Display the new prompt */
    (void) textcolor (COLOR_TEXTHIGH);
    cputsxy ((MAX_X - PromptLength) / 2, MAX_Y-1, ActivePrompt);

    /* Restore the old color */
    (void) textcolor (PromptColor);
}



static void HelpPrompt (void)
/* Display a prompt line mentioning the help key */
{
    DisplayPrompt ("Press F1 for help");
}



static void AnyKeyPrompt (void)
{
    DisplayPrompt ("Press any key to continue");
}



static char IsAbortKey (char C)
/* Return true if C is an abort key */
{
#if defined(CH_ESC)
    if (C == CH_ESC) {
        return 1;
    }
#endif
#if defined(CH_STOP)
    if (C == CH_STOP) {
        return 1;
    }
#endif
#if !defined(CH_ESC) && !defined(CH_STOP)
    /* Avoid compiler warning about unused parameter */
    (void) C;
#endif
    return 0;
}



static char Input (char* Prompt, char* Buf, unsigned char Count)
/* Read input from the user, return 1 on success, 0 if aborted */
{
    int Frame;
    unsigned char OldColor;
    unsigned char OldCursor;
    unsigned char x1;
    unsigned char i;
    unsigned char done;
    char c;

    /* Clear the current prompt line */
    cclearxy (0, MAX_Y-1, MAX_X);

    /* Display the new prompt */
    OldColor = textcolor (COLOR_TEXTHIGH);
    cputsxy (0, MAX_Y-1, Prompt);
    (void) textcolor (COLOR_TEXTLOW);

    /* Remember where we are, enable the cursor */
    x1 = wherex ();
    OldCursor = cursor (1);

    /* Get input and handle it */
    i = done = 0;
    do {
        c = cgetc ();
        if (isalnum (c) && i < Count) {
            Buf [i] = c;
            cputcxy (x1 + i, MAX_Y-1, c);
            ++i;
        } else if (i > 0 && c == CH_DEL) {
            --i;
            cputcxy (x1 + i, MAX_Y-1, ' ');
            gotoxy (x1 + i, MAX_Y-1);
        } else if (c == '\n') {
            Buf [i] = '\0';
            done = 1;
        } else if (IsAbortKey (c)) {
            /* Abort */
            done = 2;
        }
    } while (!done);

    /* Reset settings, display old prompt line */
    cursor (OldCursor);
    (void) textcolor (OldColor);
    DrawFrames ();
    Frame = ActiveFrame;
    ActiveFrame = -1;
    ActivateFrame (Frame, 0);

    return (done == 1);
}



static char InputHex (char* Prompt, unsigned* Val)
/* Prompt for a hexadecimal value. Return 0 on failure. */
{
    char Buf [5];
    char* P;
    char C;
    unsigned V;

    /* Read input from the user (4 digits max), check input */
    if (Input (Prompt, Buf, sizeof (Buf)-1) && isxdigit (Buf [0])) {

        /* Check the characters and convert to hex */
        P = Buf;
        V = 0;
        while ((C = *P) && isxdigit (C)) {
            V <<= 4;
            if (isdigit (C)) {
                C -= '0';
            } else {
                C = toupper (C) - ('A' - 10);
            }
            V += C;
            ++P;
        }

        /* Assign the value */
        *Val = V;

        /* Success */
        return 1;

    } else {

        /* Failure */
        return 0;

    }
}



static void ErrorPrompt (const char* Msg)
/* Display an error message and wait for a key */
{
    /* Save the current prompt */
    const char* OldPrompt = ActivePrompt;

    /* Display the new one */
    DisplayPrompt (Msg);

    /* Wait for a key and discard it */
    cgetc ();

    /* Restore the old prompt */
    DisplayPrompt (OldPrompt);
}



static char InputGoto (unsigned* Addr)
/* Prompt "Goto" and read an address. Print an error and return 0 on failure. */
{
    char Ok;
    Ok = InputHex ("Goto: ", Addr);
    if (!Ok) {
        ErrorPrompt ("Invalid input - press a key");
    }
    return Ok;
}



static void BreakInRomError (void)
/* Print an error message if we cannot set a breakpoint */
{
    ErrorPrompt ("Cannot set breakpoint - press a key");
}



/*****************************************************************************/
/*                            Breakpoint handling                            */
/*****************************************************************************/



static void DbgSetTmpBreak (unsigned Addr)
/* Set a breakpoint */
{
    BreakPoint* B = DbgGetBreakSlot ();
    B->bk_addr    = Addr;
    B->bk_use     = BRK_TMP;
}



static void DbgToggleUserBreak (unsigned Addr)
/* Set a breakpoint */
{
    register BreakPoint* B = DbgIsBreak (Addr);

    if (B) {
        /* We have a breakpoint, remove it */
        B->bk_use = BRK_EMPTY;
        --DbgBreakCount;
    } else {
        /* We don't have a breakpoint, set one */
        if (DbgBreakCount >= MAX_USERBREAKS) {
            ErrorPrompt ("Too many breakpoints - press a key");
        } else {
            /* Test if we can set a breakpoint at that address */
            if (!DbgIsRAM (Addr)) {
                BreakInRomError ();
            } else {
                /* Set the breakpoint */
                B = DbgGetBreakSlot ();
                B->bk_addr = Addr;
                B->bk_use  = BRK_USER;
                ++DbgBreakCount;
            }
        }
    }
}



static void DbgResetTmpBreaks (void)
/* Reset all temporary breakpoints */
{
    unsigned char i;
    BreakPoint* B = DbgBreaks;

    for (i = 0; i < MAX_USERBREAKS; ++i) {
        if (B->bk_use == BRK_TMP) {
            B->bk_use = BRK_EMPTY;
        }
        ++B;
    }
}



static unsigned char DbgTmpBreaksOk (void)
/* Check if the temporary breakpoints can be set, if so, return 1, if not,
** reset them all and return 0.
*/
{
    unsigned char i;
    BreakPoint* B = DbgBreaks;
    for (i = 0; i < MAX_USERBREAKS; ++i) {
        if (B->bk_use == BRK_TMP && !DbgIsRAM (B->bk_addr)) {
            BreakInRomError ();
            DbgResetTmpBreaks ();
            return 0;
        }
        ++B;
    }
    return 1;
}



/*****************************************************************************/
/*                          Assembler window stuff                           */
/*****************************************************************************/



static unsigned AsmBack (unsigned mem, unsigned char lines)
/* Go back in the assembler window the given number of lines (calculate
** new start address).
*/
{
    unsigned cur;
    unsigned adr [32];
    unsigned char in;

    unsigned offs = 6;
    while (1) {
        in = 0;
        cur = mem - (lines * 3) - offs;
        while (1) {
            cur += DbgDisAsmLen (cur);
            adr [in] = cur;
            in = (in + 1) & 0x1F;
            if (cur >= mem) {
                if (cur == mem || offs == 12) {
                    /* Found */
                    return adr [(in - lines - 1) & 0x1F];
                } else {
                    /* The requested address is inside an instruction, go back
                    ** one more byte and try again.
                    */
                    ++offs;
                    break;
                }
            }
        }
    }
}



static unsigned UpdateAsm (void)
/* Update the assembler window starting at the given address */
{
    char buf [MAX_X];
    unsigned char len;
    unsigned char y;
    unsigned char width = AsmFrame.fd_width;
    unsigned char x = AsmFrame.fd_x1 + 1;
    unsigned      m = AsmBack (AsmAddr, 2);

    for (y = AsmFrame.fd_y1+1; y < AsmFrame.fd_y2; ++y) {
        len = DbgDisAsm (m, buf, width);
        if (m == brk_pc) {
            buf [4] = '-';
            buf [5] = '>';
        }
        if (DbgIsBreak (m)) {
            buf [5] = '*';
        }
        if (m == AsmAddr) {
            revers (1);
            cputsxy (1, y, buf);
            revers (0);
        } else {
            cputsxy (1, y, buf);
        }
        m += len;
    }
    return m;
}



static unsigned AsmArg16 (void)
/* Return a 16 bit argument */
{
    return *(unsigned*)(AsmAddr+1);
}



static void AsmFollow (void)
/* Follow the current instruction */
{
    switch (*(unsigned char*) AsmAddr) {

        case OPC_JMP:
        case OPC_JSR:
            AsmAddr = AsmArg16 ();
            break;

        case OPC_JMPIND:
            AsmAddr = *(unsigned*)AsmArg16 ();
            break;

        case OPC_BPL:
        case OPC_BMI:
        case OPC_BVC:
        case OPC_BVS:
        case OPC_BCC:
        case OPC_BCS:
        case OPC_BNE:
        case OPC_BEQ:
            AsmAddr = AsmAddr + 2 + *(signed char*)(AsmAddr+1);
            break;

        case OPC_RTS:
            AsmAddr = (*(unsigned*) (DbgSP + 0x101) + 1);
            break;

        case OPC_RTI:
            AsmAddr = *(unsigned*) (DbgSP + 0x102);
            break;

    }
}



static void AsmHome (void)
/* Set the cursor to home position */
{
    AsmAddr = brk_pc;
}



static void InitAsm (void)
/* Initialize the asm window */
{
    AsmHome ();
    UpdateAsm ();
}



static char AsmHandler (void)
/* Get characters and handle them */
{
    char c;
    unsigned Last;

    while (1) {

        /* Update the window contents */
        Last = UpdateAsm ();

        /* Read and handle input */
        switch (c = GetKeyUpdate ()) {

            case  '+':
                AsmAddr = Last;
                break;

            case '-':
                AsmAddr = AsmBack (AsmAddr, AsmFrame.fd_height);
                break;

            case 't':
#ifdef CH_F2
            case CH_F2:
#endif
                DbgToggleUserBreak (AsmAddr);
                break;

            case 'f':
                AsmFollow ();
                break;

            case 'g':
                InputGoto (&AsmAddr);
                break;

            case 'o':
                AsmHome ();
                break;

            case 'p':
                brk_pc = AsmAddr;
                break;

            case 'a':
#ifdef CH_CURS_UP
            case CH_CURS_UP:
#endif
                AsmAddr = AsmBack (AsmAddr, 1);
                break;

            case 'z':
#ifdef CH_CURS_DOWN
            case CH_CURS_DOWN:
#endif
                AsmAddr += DbgDisAsmLen (AsmAddr);
                break;

            default:
                return c;

        }
    }
}



/*****************************************************************************/
/*                           Register window stuff                           */
/*****************************************************************************/



static unsigned UpdateReg (void)
/* Update the register window */
{
    unsigned char x1 = RegFrame.fd_x1 + 5;
    unsigned char x2 = x1 + 2;
    unsigned char y = RegFrame.fd_y1;

    /* Print the register contents */
    gotoxy (x1, ++y);   cputhex16 (brk_pc);
    gotoxy (x2, ++y);   cputhex8  (brk_sr);
    gotoxy (x2, ++y);   cputhex8  (brk_a);
    gotoxy (x2, ++y);   cputhex8  (brk_x);
    gotoxy (x2, ++y);   cputhex8  (brk_y);
    gotoxy (x2, ++y);   cputhex8  (DbgSP);
    gotoxy (x1, ++y);   cputhex16 (DbgCS);
    gotoxy (x1, ++y);   cputhex16 (DbgHI);

    /* Not needed */
    return 0;
}



static void InitReg (void)
/* Initialize the register window */
{
    UpdateReg ();
}



static char RegHandler (void)
/* Get characters and handle them */
{
    return GetKeyUpdate ();
}



/*****************************************************************************/
/*                             Stack window stuff                            */
/*****************************************************************************/



static unsigned UpdateStack (void)
/* Update the stack window */
{
    unsigned char mem = StackAddr;
    unsigned char x1 = StackFrame.fd_x1 + 1;
    unsigned char x2 = x1 + 6;
    unsigned char y;

    for (y = StackFrame.fd_y2-1; y > StackFrame.fd_y1; --y) {
        gotoxy (x1, y);
        cputhex8 (mem);
        gotoxy (x2, y);
        cputhex8 (* (unsigned char*) (mem + 0x100));
        ++mem;
    }
    return mem;
}



static void StackHome (void)
/* Set the cursor to home position */
{
    StackAddr = DbgSP + 1;
}



static void InitStack (void)
/* Initialize the stack window */
{
    StackHome ();
    UpdateStack ();
}



static char StackHandler (void)
/* Get characters and handle them */
{
    char c;
    unsigned char BytesPerPage = StackFrame.fd_height;

    while (1) {

        /* Read and handle input */
        switch (c = GetKeyUpdate ()) {

            case  '+':
                StackAddr += BytesPerPage;
                break;

            case '-':
                StackAddr -= BytesPerPage;
                break;

            case 'o':
                StackHome ();
                break;

            case 'a':
#ifdef CH_CURS_UP:
            case CH_CURS_UP:
#endif
                --StackAddr;
                break;

            case 'z':
#ifdef CH_CURS_DOWN
            case CH_CURS_DOWN:
#endif
                ++StackAddr;
                break;

            default:
                return c;

        }

        /* Update the window contents */
        UpdateStack ();
    }
}



/*****************************************************************************/
/*                           C Stack window stuff                            */
/*****************************************************************************/



static unsigned UpdateCStack (void)
/* Update the C stack window */
{
    unsigned mem     = CStackAddr;
    unsigned char x  = CStackFrame.fd_x1 + 5;
    unsigned char y;

    for (y = CStackFrame.fd_y2-1; y > CStackFrame.fd_y1; --y) {
        gotoxy (x, y);
        cputhex16 (* (unsigned*)mem);
        mem += 2;
    }
    cputsxy (CStackFrame.fd_x1+1, CStackFrame.fd_y2-1, "->");
    return mem;
}



static void CStackHome (void)
/* Set the cursor to home position */
{
    CStackAddr = DbgCS;
}



static void InitCStack (void)
/* Initialize the C stack window */
{
    CStackHome ();
    UpdateCStack ();
}



static char CStackHandler (void)
/* Get characters and handle them */
{
    char c;
    unsigned char BytesPerPage = CStackFrame.fd_height * 2;

    while (1) {

        /* Read and handle input */
        switch (c = GetKeyUpdate ()) {

            case  '+':
                CStackAddr += BytesPerPage;
                break;

            case '-':
                CStackAddr -= BytesPerPage;
                break;

            case 'o':
                CStackHome ();
                break;

            case 'a':
#ifdef CH_CURS_UP
            case CH_CURS_UP:
#endif
                CStackAddr -= 2;
                break;

            case 'z':
#ifdef CH_CURS_DOWN
            case CH_CURS_DOWN:
#endif
                CStackAddr += 2;
                break;

            default:
                return c;

        }

        /* Update the window contents */
        UpdateCStack ();
    }
}



/*****************************************************************************/
/*                             Dump window stuff                             */
/*****************************************************************************/



static unsigned UpdateDump (void)
/* Update the dump window */
{
    char Buf [MAX_X];
    unsigned char y;
    unsigned mem = DumpAddr;
    unsigned char x = DumpFrame.fd_x1 + 1;
    unsigned char* p = (unsigned char*) mem;

    for (y = DumpFrame.fd_y1+1; y < DumpFrame.fd_y2; ++y) {
        cputsxy (x, y, DbgMemDump (mem, Buf, DUMP_BYTES));
        mem += DUMP_BYTES;
    }
    return mem;
}



static void DumpHome (void)
/* Set the cursor to home position */
{
    DumpAddr = 0;
}



static char DumpHandler (void)
/* Get characters and handle them */
{
    char c;
    unsigned BytesPerPage = DumpFrame.fd_height * 8;

    while (1) {

        /* Read and handle input */
        switch (c = GetKeyUpdate ()) {

            case  '+':
                DumpAddr += BytesPerPage;
                break;

            case '-':
                DumpAddr -= BytesPerPage;
                break;

            case 'g':
                InputGoto (&DumpAddr);
                break;

            case 'o':
                DumpHome ();
                break;

            case 'a':
#ifdef CH_CURS_UP
            case CH_CURS_UP:
#endif
                DumpAddr -= 8;
                break;

            case 'z':
#ifdef CH_CURS_DOWN
            case CH_CURS_DOWN:
#endif
                DumpAddr += 8;
                break;

            default:
                return c;

        }

        /* Update the window contents */
        UpdateDump ();
    }
}



/*****************************************************************************/
/*                             Help window stuff                             */
/*****************************************************************************/



static char HelpHandler (void)
/* Get characters and handle them */
{
    /* Activate the frame */
    int OldActive = ActiveFrame;
    ActivateFrame (WIN_HELP, 1);

    /* Say that we're waiting for a key */
    AnyKeyPrompt ();

    /* Get a character and discard it */
    cgetc ();

    /* Redraw the old stuff */
    Redraw (OldActive);

    /* Done, return no char */
    return 0;
}



/*****************************************************************************/
/*                                Singlestep                                 */
/*****************************************************************************/



static unsigned GetArg16 (void)
/* Read an argument */
{
    return *(unsigned*)(brk_pc+1);
}



static unsigned GetStack16 (unsigned char Offs)
/* Fetch a 16 bit value from stack top */
{
    return *(unsigned*)(DbgSP+Offs+0x101);
}



static void SetRTSBreak (void)
/* Set a breakpoint at the return target */
{
    DbgSetTmpBreak (GetStack16 (0) + 1);
}



static void SingleStep (char StepInto)
{
    signed char Offs;

    switch (*(unsigned char*) brk_pc) {

        case OPC_JMP:
            /* Set breakpoint at target */
            DbgSetTmpBreak (GetArg16 ());
            return;

        case OPC_JMPIND:
            /* Indirect jump, ignore CPU error when crossing page */
            DbgSetTmpBreak (*(unsigned*)GetArg16 ());
            return;

        case OPC_BPL:
        case OPC_BMI:
        case OPC_BVC:
        case OPC_BVS:
        case OPC_BCC:
        case OPC_BCS:
        case OPC_BNE:
        case OPC_BEQ:
            /* Be sure not to set the breakpoint twice if this is a jump to
            ** the following instruction.
            */
            Offs = ((signed char*)brk_pc)[1];
            if (Offs) {
                DbgSetTmpBreak (brk_pc + Offs + 2);
            }
            break;

        case OPC_RTS:
            /* Set a breakpoint at the return target */
            SetRTSBreak ();
            return;

        case OPC_RTI:
            /* Set a breakpoint at the return target */
            DbgSetTmpBreak (GetStack16 (1));
            return;

        case OPC_JSR:
            if (StepInto) {
                /* Set breakpoint at target */
                DbgSetTmpBreak (GetArg16 ());
                return;
            }
            break;
    }

    /* Place a breakpoint behind the instruction */
    DbgSetTmpBreak (brk_pc + DbgDisAsmLen (brk_pc));
}



/*****************************************************************************/
/*                        High level window handling                         */
/*****************************************************************************/



static void RedrawStatic (char Frame)
/* Redraw static display stuff */
{
    /* Reset the active frame */
    ActiveFrame = -1;

    /* Clear the screen hide the cursor */
    (void) bordercolor (COLOR_BORDER);
    (void) bgcolor (COLOR_BACKGROUND);
    clrscr ();
    cursor (0);

    /* Build the frame layout of the screen */
    (void) textcolor (COLOR_FRAMELOW);
    DrawFrames ();

    /* Draw the prompt line */
    HelpPrompt ();

    /* Activate the active frame */
    ActivateFrame (Frame, 0);
}



static void Redraw (char Frame)
/* Redraw the display in case it's garbled */
{
    /* Redraw the static stuff */
    RedrawStatic (Frame);

    /* Init the window contents */
    UpdateAsm ();
    UpdateReg ();
    UpdateStack ();
    UpdateCStack ();
    UpdateDump ();
}



static char GetKeyUpdate (void)
/* Wait for a key updating the windows in the background */
{
    static unsigned char Win;

    /* While there are no keys... */
    while (!kbhit ()) {

        switch (Win) {

            case 0:
                UpdateAsm ();
                break;

            case 1:
                UpdateStack ();
                break;

            case 2:
                UpdateCStack ();
                break;

            case 3:
                UpdateDump ();
                break;
        }

        Win = (Win + 1) & 0x03;

    }

    /* We have a key - return it */
    return cgetc ();
}



/*****************************************************************************/
/*                       Externally visible functions                        */
/*****************************************************************************/



void DbgEntry (void)
/* Start up the debugger */
{
    static unsigned char FirstTime = 1;
    char c;
    char done;

    /* If this is the first call, setup the display */
    if (FirstTime) {
        FirstTime = 0;

        /* Draw the window, default active frame is ASM frame */
        RedrawStatic (WIN_ASM);
        InitAsm ();
        InitReg ();
        InitStack ();
        InitCStack ();
        UpdateDump ();
    }

    /* Only initialize variables here, don't do a display update. The actual
    ** display update will be done while waiting for user input.
    */
    AsmHome ();
    UpdateReg ();               /* Must update this (static later) */
    StackHome ();
    CStackHome ();

    /* Wait for user input */
    done = 0;
    while (!done) {
        c = Frames [ActiveFrame]->fd_func ();
        switch (c) {

            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
                ActivateFrame (c - '1', 0);
                break;

            case '?':
#ifdef CH_F1
            case CH_F1:
#endif
                HelpHandler ();
                break;

            case 'u':
#ifdef CH_F3
            case CH_F3:
#endif
                /* Go until return */
                SetRTSBreak ();
                done = 1;
                break;

            case 'h':
#ifdef CH_F4
            case CH_F4:
#endif
                /* Go to cursor, only possible if cursor not at current PC */
                if (AsmAddr != brk_pc) {
                    DbgSetTmpBreak (AsmAddr);
                    done = 1;
                }
                break;

            case ' ':
#ifdef CH_F7
            case CH_F7:
#endif
                SingleStep (1);
                if (DbgTmpBreaksOk ()) {
                    /* Could set breakpoints */
                    done = 1;
                }
                break;

            case '\n':
#ifdef CH_F8
            case CH_F8:
#endif
                SingleStep (0);
                if (DbgTmpBreaksOk ()) {
                    /* Could set breakpoints */
                    done = 1;
                }
                break;

            case 'c':
            case 0:
                done = 1;
                break;

            case 's':
                /* Skip instruction */
                brk_pc += DbgDisAsmLen (brk_pc);
                InitAsm ();
                break;

            case 'r':
                /* Redraw screen */
                Redraw (ActiveFrame);
                break;

            case 'q':
                /* Quit program */
                clrscr ();
                
                /* Exit intentionally with error because one may
                **  say that DbgEntry is always abnormal. 
                */
                exit (EXIT_FAILURE);
        
        }
    }
}