-
Notifications
You must be signed in to change notification settings - Fork 0
/
megahal.c
3503 lines (2974 loc) · 82 KB
/
megahal.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
/*===========================================================================*/
/*
* Copyright (C) 1998 Jason Hutchens
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the license or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the Gnu Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*===========================================================================*/
/*
* $Id: megahal.c,v 1.10 2004/02/23 11:12:29 lfousse Exp $
*
* File: megahal.c
*
* Program: MegaHAL
*
* Purpose: To simulate a natural language conversation with a psychotic
* computer. This is achieved by learning from the user's
* input using a third-order Markov model on the word level.
* Words are considered to be sequences of characters separated
* by whitespace and punctuation. Replies are generated
* randomly based on a keyword, and they are scored using
* measures of surprise.
*
* Author: Mr. Jason L. Hutchens (http://www.amristar.com.au/~hutch/)
*
* WWW: http://megahal.sourceforge.net
*
* Compilation Notes
* =================
*
* When compiling, be sure to link with the maths library so that the
* log() function can be found.
*
* On the Macintosh, add the library SpeechLib to your project. It is
* very important that you set the attributes to Import Weak. You can
* do this by selecting the lib and then use Project Inspector from the
* Window menu.
*
* CREDITS
* =======
*
* Amiga (AmigaOS)
* ---------------
* Dag Agren ([email protected])
*
* DEC (OSF)
* ---------
* Jason Hutchens ([email protected])
*
* Macintosh
* ---------
* Paul Baxter ([email protected])
* Doug Turner ([email protected])
*
* PC (Linux)
* ----------
* Jason Hutchens ([email protected])
*
* PC (OS/2)
* ---------
* Bjorn Karlowsky (?)
*
* PC (Windows 3.11)
* -----------------
* Jim Crawford ([email protected])
*
* PC (Windows '95)
* ----------------
* Jason Hutchens ([email protected])
*
* PPC (Linux)
* -----------
* Lucas Vergnettes ([email protected])
*
* SGI (Irix)
* ----------
* Jason Hutchens ([email protected])
*
* Sun (SunOS)
* -----------
* Jason Hutchens ([email protected])
*/
/*===========================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <unistd.h>
#include <getopt.h>
#include <string.h>
#include <signal.h>
#include <math.h>
#include <time.h>
#include <ctype.h>
#if defined(__mac_os)
#include <types.h>
#include <Speech.h>
#else
#include <sys/types.h>
#endif
#include "megahal.h"
#if defined(DEBUG)
#include "debug.h"
#endif
#define P_THINK 40
#define D_KEY 100000
#define V_KEY 50000
#define D_THINK 500000
#define V_THINK 250000
#define MIN(a,b) ((a)<(b))?(a):(b)
#define COOKIE "MegaHALv8"
#define TIMEOUT 1
#define DEFAULT "."
#define COMMAND_SIZE (sizeof(command)/sizeof(command[0]))
#define BYTE1 unsigned char
#define BYTE2 unsigned short
#define BYTE4 unsigned long
#ifdef __mac_os
#define bool Boolean
#endif
#ifdef DOS
#define SEP "\\"
#else
#define SEP "/"
#endif
#ifdef AMIGA
#undef toupper
#define toupper(x) ToUpper(x)
#undef tolower
#define tolower(x) ToLower(x)
#undef isalpha
#define isalpha(x) IsAlpha(_AmigaLocale,x)
#undef isalnum
#define isalnum(x) IsAlNum(_AmigaLocale,x)
#undef isdigit
#define isdigit(x) IsDigit(_AmigaLocale,x)
#undef isspace
#define isspace(x) IsSpace(_AmigaLocale,x)
#endif
#ifndef __mac_os
#undef FALSE
#undef TRUE
typedef enum { FALSE, TRUE } bool;
#endif
typedef struct {
BYTE1 length;
char *word;
} STRING;
typedef struct {
BYTE4 size;
STRING *entry;
BYTE2 *index;
} DICTIONARY;
typedef struct {
BYTE2 size;
STRING *from;
STRING *to;
} SWAP;
typedef struct NODE {
BYTE2 symbol;
BYTE4 usage;
BYTE2 count;
BYTE2 branch;
struct NODE **tree;
} TREE;
typedef struct {
BYTE1 order;
TREE *forward;
TREE *backward;
TREE **context;
DICTIONARY *dictionary;
} MODEL;
typedef enum { UNKNOWN, QUIT, EXIT, SAVE, DELAY, HELP, SPEECH, VOICELIST, VOICE, BRAIN, QUIET} COMMAND_WORDS;
typedef struct {
STRING word;
char *helpstring;
COMMAND_WORDS command;
} COMMAND;
/*===========================================================================*/
static int width=75;
static int order=5;
static bool typing_delay=FALSE;
static bool noprompt=FALSE;
static bool speech=FALSE;
static bool quiet=FALSE;
static bool nowrap=FALSE;
static bool nobanner=FALSE;
static char *errorfilename = "megahal.log";
static char *statusfilename = "megahal.txt";
static DICTIONARY *words=NULL;
static DICTIONARY *greets=NULL;
static MODEL *model=NULL;
static FILE *errorfp;
static FILE *statusfp;
static DICTIONARY *ban=NULL;
static DICTIONARY *aux=NULL;
/*static DICTIONARY *fin=NULL; not used */
static DICTIONARY *grt=NULL;
static SWAP *swp=NULL;
static bool used_key;
static char *directory=NULL;
static char *last=NULL;
static COMMAND command[] = {
{ { 4, "QUIT" }, "quits the program and saves MegaHAL's brain", QUIT },
{ { 4, "EXIT" }, "exits the program *without* saving MegaHAL's brain", EXIT },
{ { 4, "SAVE" }, "saves the current MegaHAL brain", SAVE },
{ { 5, "DELAY" }, "toggles MegaHAL's typing delay (off by default)", DELAY },
{ { 6, "SPEECH" }, "toggles MegaHAL's speech (off by default)", SPEECH },
{ { 6, "VOICES" }, "list available voices for speech", VOICELIST },
{ { 5, "VOICE" }, "switches to voice specified", VOICE },
{ { 5, "BRAIN" }, "change to another MegaHAL personality", BRAIN },
{ { 4, "HELP" }, "displays this message", HELP },
{ { 5, "QUIET" }, "toggles MegaHAL's responses (on by default)",QUIET},
/*
{ { 5, "STATS" }, "Display stats", STATS},
{ { 5, "STATS-SESSION" }, "Display stats for this session only",STATS_SESSION},
{ { 5, "STATS-ALL" },"Display stats for the whole lifetime",STATS-ALL},
*/
};
#ifdef AMIGA
struct Locale *_AmigaLocale;
#endif
#ifdef __mac_os
Boolean gSpeechExists = false;
SpeechChannel gSpeechChannel = nil;
#endif
/* FIXME - these need to be static */
static void add_aux(MODEL *, DICTIONARY *, STRING);
static void add_key(MODEL *, DICTIONARY *, STRING);
static void add_node(TREE *, TREE *, int);
static void add_swap(SWAP *, char *, char *);
static TREE *add_symbol(TREE *, BYTE2);
static BYTE2 add_word(DICTIONARY *, STRING);
static int babble(MODEL *, DICTIONARY *, DICTIONARY *);
static bool boundary(char *, int);
static void capitalize(char *);
static void changevoice(DICTIONARY *, int);
static void change_personality(DICTIONARY *, unsigned int, MODEL **);
static void delay(char *);
static void die(int);
static bool dissimilar(DICTIONARY *, DICTIONARY *);
static void error(char *, char *, ...);
static float evaluate_reply(MODEL *, DICTIONARY *, DICTIONARY *);
static COMMAND_WORDS execute_command(DICTIONARY *, int *);
static void exithal(void);
static TREE *find_symbol(TREE *, int);
static TREE *find_symbol_add(TREE *, int);
static BYTE2 find_word(DICTIONARY *, STRING);
static char *generate_reply(MODEL *, DICTIONARY *);
static void help(void);
static void ignore(int);
static bool initialize_error(char *);
#ifdef __mac_os
static bool initialize_speech(void);
#endif
static bool initialize_status(char *);
static void learn(MODEL *, DICTIONARY *);
static void listvoices(void);
static void make_greeting(DICTIONARY *);
static void make_words(char *, DICTIONARY *);
static DICTIONARY *new_dictionary(void);
static char *read_input(char *);
static void save_model(char *, MODEL *);
#ifdef __mac_os
static char *strdup(const char *);
#endif
static void upper(char *);
static void write_input(char *);
static void write_output(char *);
#if defined(DOS) || defined(__mac_os)
static void usleep(int);
#endif
static char *format_output(char *);
static void free_dictionary(DICTIONARY *);
static void free_model(MODEL *);
static void free_tree(TREE *);
static void free_word(STRING);
static void free_words(DICTIONARY *);
static void initialize_context(MODEL *);
static void initialize_dictionary(DICTIONARY *);
static DICTIONARY *initialize_list(char *);
static SWAP *initialize_swap(char *);
static void load_dictionary(FILE *, DICTIONARY *);
static bool load_model(char *, MODEL *);
static void load_personality(MODEL **);
static void load_tree(FILE *, TREE *);
static void load_word(FILE *, DICTIONARY *);
static DICTIONARY *make_keywords(MODEL *, DICTIONARY *);
static char *make_output(DICTIONARY *);
static MODEL *new_model(int);
static TREE *new_node(void);
static SWAP *new_swap(void);
static bool print_header(FILE *);
static bool progress(char *, int, int);
static DICTIONARY *reply(MODEL *, DICTIONARY *);
static void save_dictionary(FILE *, DICTIONARY *);
static void save_tree(FILE *, TREE *);
static void save_word(FILE *, STRING);
static int search_dictionary(DICTIONARY *, STRING, bool *);
static int search_node(TREE *, int, bool *);
static int seed(MODEL *, DICTIONARY *);
static void show_dictionary(DICTIONARY *);
static void speak(char *);
static bool status(char *, ...);
static void train(MODEL *, char *);
static void typein(char);
static void update_context(MODEL *, int);
static void update_model(MODEL *, int);
static bool warn(char *, char *, ...);
static int wordcmp(STRING, STRING);
static bool word_exists(DICTIONARY *, STRING);
static int rnd(int);
/* Function: setnoprompt
Purpose: Set noprompt variable.
*/
void megahal_setnoprompt(void)
{
noprompt = TRUE;
}
void megahal_setnowrap (void)
{
nowrap = TRUE;
}
void megahal_setnobanner (void)
{
nobanner = TRUE;
}
void megahal_seterrorfile(char *filename)
{
errorfilename = filename;
}
void megahal_setstatusfile(char *filename)
{
statusfilename = filename;
}
void megahal_setdirectory (char *dir)
{
directory = dir;
}
/*
megahal_initialize --
Initialize various brains and files.
Results:
None.
*/
void megahal_initialize(void)
{
errorfp = stderr;
statusfp = stdout;
initialize_error(errorfilename);
initialize_status(statusfilename);
ignore(0);
#ifdef AMIGA
_AmigaLocale=OpenLocale(NULL);
#endif
#ifdef __mac_os
gSpeechExists = initialize_speech();
#endif
if(!nobanner)
fprintf(stdout,
"+------------------------------------------------------------------------+\n"
"| |\n"
"| # # ###### #### ## # # ## # |\n"
"| ## ## # # # # # # # # # # ### |\n"
"| # ## # ##### # # # ###### # # # # # |\n"
"| # # # # ### ###### # # ###### # # # ### |\n"
"| # # # # # # # # # # # # # # # # |\n"
"| # # ###### #### # # # # # # ###### # ###r6 |\n"
"| |\n"
"| Copyright(C) 1998 Jason Hutchens |\n"
"+------------------------------------------------------------------------+\n"
);
words = new_dictionary();
greets = new_dictionary();
change_personality(NULL, 0, &model);
}
/*
megahal_do_reply --
Take string as input, and return allocated string as output. The
user is responsible for freeing this memory.
*/
char *megahal_do_reply(char *input, int log)
{
char *output = NULL;
if (log != 0)
write_input(input); /* log input if so desired */
upper(input);
make_words(input, words);
learn(model, words);
output = generate_reply(model, words);
capitalize(output);
return output;
}
/*
megahal_learn_no_reply --
Take string as input, update model but don't generate reply.
*/
void megahal_learn_no_reply(char *input, int log)
{
if (log != 0)
write_input(input); /* log input if so desired */
upper(input);
make_words(input, words);
learn(model, words);
}
/*
megahal_initial_greeting --
This function returns an initial greeting. It can be used to start
Megahal conversations, but it isn't necessary.
*/
char *megahal_initial_greeting(void)
{
char *output;
make_greeting(greets);
output = generate_reply(model, greets);
return output;
}
/*
megahal_output --
This function pretty prints output.
Wrapper function to have things in the right namespace.
*/
void megahal_output(char *output)
{
if(!quiet)
write_output(output);
}
/*
megahal_input --
Get a string from stdin, using a prompt.
*/
char *megahal_input(char *prompt)
{
if (noprompt)
return read_input("");
else
return read_input(prompt);
}
/*
megahal_command --
Check to see if input is a megahal command, and if so, act upon it.
Returns 1 if it is a command, 0 if it is not.
*/
int megahal_command(char *input)
{
int position = 0;
char *output;
make_words(input,words);
switch(execute_command(words, &position)) {
case EXIT:
exithal();
break;
case QUIT:
save_model("megahal.brn", model);
exithal();
break;
case SAVE:
save_model("megahal.brn", model);
break;
case DELAY:
typing_delay=!typing_delay;
printf("MegaHAL typing is now %s.\n", typing_delay?"on":"off");
return 1;
case SPEECH:
speech=!speech;
printf("MegaHAL speech is now %s.\n", speech?"on":"off");
return 1;
case HELP:
help();
return 1;
case VOICELIST:
listvoices();
return 1;
case VOICE:
changevoice(words, position);
return 1;
case BRAIN:
change_personality(words, position, &model);
make_greeting(greets);
output=generate_reply(model, greets);
write_output(output);
return 1;
case QUIET:
quiet=!quiet;
return 1;
default:
return 0;
}
return 0;
}
/*
megahal_cleanup --
Clean up everything. Prepare for exit.
*/
void megahal_cleanup(void)
{
save_model("megahal.brn", model);
#ifdef AMIGA
CloseLocale(_AmigaLocale);
#endif
}
/*---------------------------------------------------------------------------*/
/*
* Function: Execute_Command
*
* Purpose: Detect whether the user has typed a command, and
* execute the corresponding function.
*/
COMMAND_WORDS execute_command(DICTIONARY *words, int *position)
{
register unsigned int i;
register unsigned int j;
/*
* If there is only one word, then it can't be a command.
*/
*position=words->size+1;
if(words->size<=1) return(UNKNOWN);
/*
* Search through the word array. If a command prefix is found,
* then try to match the following word with a command word. If
* a match is found, then return a command identifier. If the
* Following word is a number, then change the judge. Otherwise,
* continue the search.
*/
for(i=0; i<words->size-1; ++i)
/*
* The command prefix was found.
*/
if(words->entry[i].word[words->entry[i].length - 1] == '#') {
/*
* Look for a command word.
*/
for(j = 0; j < COMMAND_SIZE; ++j)
if(wordcmp(command[j].word, words->entry[i + 1]) == 0) {
*position = i + 1;
return(command[j].command);
}
}
return(UNKNOWN);
}
/*---------------------------------------------------------------------------*/
/*
* Function: ExitHAL
*
* Purpose: Terminate the program.
*/
void exithal(void)
{
#ifdef __mac_os
/*
* Must be called because it does use some system memory
*/
if (gSpeechChannel) {
StopSpeech(gSpeechChannel);
DisposeSpeechChannel(gSpeechChannel);
gSpeechChannel = nil;
}
#endif
exit(0);
}
/*---------------------------------------------------------------------------*/
/*
* Function: Read_Input
*
* Purpose: Read an input string from the user.
*/
char *read_input(char *prompt)
{
static char *input=NULL;
bool finish;
int length;
int c;
/*
* Perform some initializations. The finish boolean variable is used
* to detect a double line-feed, while length contains the number of
* characters in the input string.
*/
finish=FALSE;
length=0;
if(input==NULL) {
input=(char *)malloc(sizeof(char));
if(input==NULL) {
error("read_input", "Unable to allocate the input string");
return(input);
}
}
/*
* Display the prompt to the user.
*/
fprintf(stdout, prompt);
fflush(stdout);
/*
* Loop forever, reading characters and putting them into the input
* string.
*/
while(TRUE) {
/*
* Read a single character from stdin.
*/
c=getc(stdin);
/*
* If the character is a line-feed, then set the finish variable
* to TRUE. If it already is TRUE, then this is a double line-feed,
* in which case we should exit. After a line-feed, display the
* prompt again, and set the character to the space character, as
* we don't permit linefeeds to appear in the input.
*/
if((char)(c)=='\n') {
if(finish==TRUE) break;
fprintf(stdout, prompt);
fflush(stdout);
finish=TRUE;
c=32;
} else {
finish=FALSE;
}
/*
* Re-allocate the input string so that it can hold one more
* character.
*/
++length;
input=(char *)realloc((char *)input,sizeof(char)*(length+1));
if(input==NULL) {
error("read_input", "Unable to re-allocate the input string");
return(NULL);
}
/*
* Add the character just read to the input string.
*/
input[length-1]=(char)c;
input[length]='\0';
}
while(isspace(input[length-1])) --length;
input[length]='\0';
/*
* We have finished, so return the input string.
*/
return(input);
}
/*---------------------------------------------------------------------------*/
/*
* Function: Initialize_Error
*
* Purpose: Close the current error file pointer, and open a new one.
*/
bool initialize_error(char *filename)
{
if(errorfp!=stderr) fclose(errorfp);
if(filename==NULL) return(TRUE);
errorfp = fopen(filename, "a");
if(errorfp==NULL) {
errorfp=stderr;
return(FALSE);
}
return(print_header(errorfp));
}
/*---------------------------------------------------------------------------*/
/*
* Function: Error
*
* Purpose: Print the specified message to the error file.
*/
void error(char *title, char *fmt, ...)
{
va_list argp;
fprintf(errorfp, "%s: ", title);
va_start(argp, fmt);
vfprintf(errorfp, fmt, argp);
va_end(argp);
fprintf(errorfp, ".\n");
fflush(errorfp);
fprintf(stderr, "MegaHAL died for some reason; check the error log.\n");
exit(1);
}
/*---------------------------------------------------------------------------*/
bool warn(char *title, char *fmt, ...)
{
va_list argp;
fprintf(errorfp, "%s: ", title);
va_start(argp, fmt);
vfprintf(errorfp, fmt, argp);
va_end(argp);
fprintf(errorfp, ".\n");
fflush(errorfp);
fprintf(stderr, "MegaHAL emitted a warning; check the error log.\n");
return(TRUE);
}
/*---------------------------------------------------------------------------*/
/*
* Function: Initialize_Status
*
* Purpose: Close the current status file pointer, and open a new one.
*/
bool initialize_status(char *filename)
{
if(statusfp!=stdout) fclose(statusfp);
if(filename==NULL) return(FALSE);
statusfp=fopen(filename, "a");
if(statusfp==NULL) {
statusfp=stdout;
return(FALSE);
}
return(print_header(statusfp));
}
/*---------------------------------------------------------------------------*/
/*
* Function: Status
*
* Purpose: Print the specified message to the status file.
*/
bool status(char *fmt, ...)
{
va_list argp;
va_start(argp, fmt);
vfprintf(statusfp, fmt, argp);
va_end(argp);
fflush(statusfp);
return(TRUE);
}
/*---------------------------------------------------------------------------*/
/*
* Function: Print_Header
*
* Purpose: Display a copyright message and timestamp.
*/
bool print_header(FILE *file)
{
time_t clock;
char timestamp[1024];
struct tm *local;
clock=time(NULL);
local=localtime(&clock);
strftime(timestamp, 1024, "Start at: [%Y/%m/%d %H:%M:%S]\n", local);
fprintf(file, "MegaHALv8\n");
fprintf(file, "Copyright (C) 1998 Jason Hutchens\n");
fprintf(file, timestamp);
fflush(file);
return(TRUE);
}
/*---------------------------------------------------------------------------*/
/*
* Function: Write_Output
*
* Purpose: Display the output string.
*/
void write_output(char *output)
{
char *formatted;
char *bit;
capitalize(output);
speak(output);
width=75;
formatted=format_output(output);
delay(formatted);
width=64;
formatted=format_output(output);
bit=strtok(formatted, "\n");
if(bit==NULL) (void)status("MegaHAL: %s\n", formatted);
while(bit!=NULL) {
(void)status("MegaHAL: %s\n", bit);
bit=strtok(NULL, "\n");
}
}
/*---------------------------------------------------------------------------*/
/*
* Function: Capitalize
*
* Purpose: Convert a string to look nice.
*/
void capitalize(char *string)
{
register unsigned int i;
bool start=TRUE;
for(i=0; i<strlen(string); ++i) {
if(isalpha(string[i])) {
if(start==TRUE) string[i]=(char)toupper((int)string[i]);
else string[i]=(char)tolower((int)string[i]);
start=FALSE;
}
if((i>2)&&(strchr("!.?", string[i-1])!=NULL)&&(isspace(string[i])))
start=TRUE;
}
}
/*---------------------------------------------------------------------------*/
/*
* Function: Upper
*
* Purpose: Convert a string to its uppercase representation.
*/
void upper(char *string)
{
register unsigned int i;
for(i=0; i<strlen(string); ++i) string[i]=(char)toupper((int)string[i]);
}
/*---------------------------------------------------------------------------*/
/*
* Function: Write_Input
*
* Purpose: Log the user's input
*/
void write_input(char *input)
{
char *formatted;
char *bit;
width=64;
formatted=format_output(input);
bit=strtok(formatted, "\n");
if(bit==NULL) (void)status("User: %s\n", formatted);
while(bit!=NULL) {
(void)status("User: %s\n", bit);
bit=strtok(NULL, "\n");
}
}
/*---------------------------------------------------------------------------*/
/*
* Function: Format_Output
*
* Purpose: Format a string to display nicely on a terminal of a given
* width.
*/
static char *format_output(char *output)
{
static char *formatted=NULL;
register unsigned int i,j,c;
int l;
if(formatted==NULL) {
formatted=(char *)malloc(sizeof(char));
if(formatted==NULL) {
error("format_output", "Unable to allocate formatted");
return("ERROR");
}
}
formatted=(char *)realloc((char *)formatted, sizeof(char)*(strlen(output)+2));