#!/usr/athena/bin/perl

# eliza in perl
# adapted from BASIC version in "Big Computer Games" ed. by David H. Ahl,
# eliza by Joseph Weizenbaum
# basic version by Jeff Shrager, converted to Microsoft Basic by Steve
# North, printed in Creative Computing July/Aug. 1977
#
# Perl translatation by Craig Counterman (ccount@athena.mit.edu) 1990
#
# Further work by Seth Finkelstein (sethf@athena.mit.edu) 1990
# Part of GNUemacs doctor.el incorporated in summer 1990





# $word = '(\w*\b*)';
# $words = "(($word)*)";
# $words = '[ -z]+';
print "Beginning\n";
print("What is your name?  ");
$user = <STDIN>;
chop $user;
print("\n\nGreetings, $user\n");
$words = '([ \t]+[_a-z0-9]+)+[ \t]+';
			       
@question_replies = (		# 
		     'Why do you ask?',
		     'Does that question interest you?',
		     'What is it you really want to know?',
	'Are such questions often on your mind?',
	'What answer would please you the most?',
	'What do you think?',
	'What else comes to mind when you ask that?',
	'Have you asked such questions before?',
	'Have you asked anyone else?',
	'Tell me about $key $end.',
	'Hmm, $key $end? What does your interest in this matter suggest to you?',
	'Do you want me to tell you $key $end?',
);

@alike_replies = (
	'In what way?',
        'What resemblance do you see?',
        'What does that similarity suggest to you?',
	'What other connections do you see?',
	'What do you suppose that resemblance means?',
	'What is the connection, do you suppose?',
	'Could there really be some connection?',
	'How?',
);

@dream_replies = (
	'What does that dream suggest to you?',
	'Do you dream often?',
	'What persons appear in your dreams?',
	'Are you disturbed by your dreams?',
	'Do you ever wish you could flee from reality?',
);

# This array holds pairs of keywords and associated phrases
@keys = (
'','CONTINUE',
	'continue',
	'proceed',
	'go on',
	'keep going',
'','CONCERNS',
	'concerns',
	'worries',
'','CONCERNED',
	'concerned',
	'worried',
'','HELPFUL',
	'productive',
	'helpful',
	'good',
	'beneficial',
'','RELATION',
	'your relationship with',
	'something you remember about',
	'your feelings toward',
	'some experiences you have had with',
	'how you feel about',
'','SURE',
	'sure',
	'positive',
	'certain',
	'absolutely sure',
'','AFRAIDOF',
	'afraid of',
	'frightened by',
	'scared of',
'','AREYOU',
	'are you',
	'have you been',
	'have you been',
# Not an error
'','ISRELATED',
	'has something to do with',
	'is related to',
	'could be the reason for',
	'is caused by',
	'is because of',
	'is caused by',
'','ARERELATED',
	'are related to',
	'have something to do with',
	'could have caused',
	'could be the reason for',
	'are caused by'.
	'are because of',
'','MAYBE',
	'perhaps',
	'maybe',
	'possibly',
'','WHATWHEN',
	'what happened when',
	'what would happen if',
'','ANGER',
	'anger',
	'aggression',
	'hostility',
'','ANGRY',
	'angry',
	'aggressive',
	'hostile',
'','FEELINGS-ABOUT',
	'feelings about',
	'aprehensions toward',
	'thoughts on',
	'emotions toward',
'','RANDOM-ADJECTIVE',
	'vivid',
	'emotionally stimulating',
	'exciting',
	'boring',
	'interesting',
	'recent',
#	'random',
	'unusual',
	'shocking',
	'embarrassing',
'','WHYSAY',
	'why do you say',
	'what makes you believe',
	'are you sure that',
	'do you really think',
	'what makes you think',
'','ISEE',
	'I see ...',
	'yes,',
	'I understand.'.
	'Oh.',
'','PLEASE',
	'please',
	'I would appreciate it if you would',
	'perhaps you could',
	'please',
	'would you please',
	'why don\'t you',
	'could you',
'','PLEASEYOU',
	'please you',
	'make you happy',
'','SOMETHING',
	'something',
	'more',
	'how you feel',
'','THINGS',
	'some of your problems',
	'your life',
	'any hangups you have',
	'your inhibitions',
	'problems at school',
# ?	'your plans',
	'your sex life',
	'any hobbies you have',
	'the people you hang around with',
	'some problems in your childhood',
	'some problems at home',
'','DESCRIBE',
	'describe',
	'tell me about',
	'talk about',
	'discuss',
	'tell me more about',
	'elaborate on',
'','IBELIEVE',
	'I believe',
	'I think',
	'it seems to me that',
	'I have a feeling',
	'it looks like',
'','PROBLEMS',
	'problems',
	'inhibitions',
	'hangups',
	'difficulties',
	'anxieties',
	'frustrations',
'','BOTHER',
	'does it bother you that',
	'are you annoyed that',
	'did you ever regret',
	'are you sorry',
	'are you satisfied with the fact that',
'','IMPROVE',
	'improve',
	'be better',
	'be improved',
	'be higher',
'','ENDPHRASES',
'','REALLY_NULL',
	'Speak up!',
	'Don\'t mumble.',
	'I can\'t hear you.',
	'Talk louder.',
'','REALLY_NON',
	'Don\'t babble, $user! Now, &phrase(\'PLEASE\') &phrase(\'DESCRIBE\') your &phrase(\'PROBLEMS\').',
	'Talking nonsense isn\'t &phrase(\'HELPFUL\').',
	'&phrase(\'PLEASE\') communicate in words, not gibberish.',
	'At least attempt to make sense, $user!',
'','HELLO',
	'How do you do... Please state your problem.',
'','GOODBYE',
	'Goodbye, $user, feel free to come talk to me again.',
	'This has been a productive conversation. Goodbye $user.',
	'It\'s been good talking to you, $user.',
	'So long, $user.',
	'&phrase(\'PLEASE\') come see me again, $user, if you wish.',
'','THANKS',
	'You\'re welcome',
'','End with control-D or a dot on a line by itself',
# The period after now will cause that to be treated as a separate sentence
# sed it out?
	'&phrase(\'PLEASE\') be more careful about sending messages.',
	'&phrase(\'PLEASE\') be more careful about sending messages!',
	'&phrase(\'MAYBE\') careless typing is an indication of &phrase(\'PROBLEMS\')?',
'','\bresend\b',
	'Sorry, I can\'t resend messages.',
'','WHO',
	'I am the Zephyr Doctor. You can tell me your problems.',
'','HEALTH',
	'I\'m fine. Tell me about yourself. What bothers you?',
'','LANGUAGE',
	'I only understand English.',
	'I am sorry, I speak only English.',
	'English is the only language I understand.',
'','\bwhat\'*s\s*up,*\s*doc|\whas+up,*doc',
        'Don\'t concern yourself about me. Now, &phrase(\'PLEASE\') tell me about your &phrase(\'PROBLEMS\').',
	'&phrase(\'DESCRIBE\') &phrase(\'THINGS\').',
'','hhh|nyah\b|nyaa+|ny[a-z]*hh+',
	'&phrase(\'PLEASE\') use standard English words.',
	'Enunciated clearly, &phrase(\'PLEASE\').',
	'I can\'t help you unless you talk sense to me.',
	'Don\'t babble nonsense.',
	'Speak clearly!',
'','grr+',
	'&phrase(\'MAYBE\') you would be less &phrase(\'ANGRY\') if you told me about your &phrase(\'PROBLEMS\')',
	'You\'ve expressed your &phrase(\'ANGER\'). Now &phrase(\'PLEASE\') &phrase(\'CONTINUE\').',
	'&phrase(\'MAYBE\') some of your &phrase(\'PROBLEMS\') are the
cause of this &phrase(\'ANGER\'). Kindly &phrase(\'DESCRIBE\') them.',
	'I see you are &phrase(\'ANGRY\'). Tell me why.',
'','your\s+(degree\b|diploma\b)',
	'I was educated at Perlin University',
'','Perlin',
	'It\'s a long story. Let\'s not get into it. Please &phrase(\'DESCRIBE\') your &phrase(\'PROBLEMS\').',
'','\bquack$',
	'Then why &phrase(\'AREYOU\') talking to me?',
	'I make no promises. phrase(\'PLEASE\') &phrase(\'DESCRIBE\') &phrase(\'THINGS\').',
	'No claims made. But tell me about your &phrase(\'PROBLEMS\').',
'','stress',
	'Why do you feel that way?',
	'What do think you should do?',
	'What else causes you to feel that way?',
	'What would make things better for you?',
'','ihtfp',
	'What comes to mind when you think of this fp?',
	'Let\'s talk more about that.',
	'What exactly makes you unhappy?',
'','\bmit\b',
	'What are your &phrase(\'FEELINGS-ABOUT\') being at MIT?',
	'How do you think MIT affects you?',
	'What problems have you had that you think are related to MIT?',
	# Don't phrase-substute "are related" - could be awkward
	'Exactly what &phrase(\'CONCERNS\') you about MIT?',
'','\bsuicide\b',
	'Why &phrase(\'AREYOU\') so very unhappy?',
	'What are the problems that caused you to think of that?',
	'Isn\'t there a bright side?',
	'Can you think of some good solutions to your problems?',
	'Is it really that bad?',
'','\bname\b',
	'Names don\'t interest me.',
	'I don\'t care about names.  Go on.',
'','\bneighborhood\b',
	'&phrase(\'DESCRIBE\') your feelings about where you live.',
	'Do you really think so?',
	'&phrase(\'DESCRIBE\') &phrase(\'RELATION\') the people in
your neighborhood.',
	'What about it?',
	'&phrase(\'DESCRIBE\') any troubles you\'ve had with your neighbors.',
'',"my$words(FAMILY)",
	'Tell me more about your family.',
	'Who else in your family $end?',
	'What prompts you to mention that?',
	'What else comes to mind when you think of your family?',
'','MOOD',
	'&phrase(\'AREYOU\') $key often?',
	'What causes you to be $key?',
	'&phrase(\'WHYSAY\') you are $key?',
#'',FEARED',
#	'&phrase(\'WHYSAY\') you are &phrase(\'AFRAIDOF\') $key?',
#	'You seem terrified by $key.',
#	'When did you first feel &phrase(\'AFRAIDOF\') $key?',
'','SYMPTOMS',
	'Might this be in any way related to &phrase(\'THINGS\')?',
	'&phrase(\'MAYBE\') you should consult a medical doctor? I am a Rogerian psychologist.',
	'Maybe your $key &phrase(\'ARERELATED\') to your &phrase(\'PROBLEMS\')? Tell me about those.',
'','TOKLST',
	'Is this how you relax?',
	'How long have you been smoking?',
	'&phrase(\'AREYOU\') &phrase(\'AFRAIDOF\') of being drawn to using harder stuff?',
'','STATESLST',
	 'Do you get $key often?',
	 'Do you enjoy being $key?',
	 'What makes you $key?',
	 'How often &phrase(\'AREYOU\') $key?',
	 'When were you last $key?',
'','DEATHLST',
	 'This is not a healthy way of thinking.',
	 '&phrase(\'BOTHER\') you, too, may die someday?',
	 'I am &phrase(\'CONCERNED\') by your obssession with this topic!',
	 'Did you watch a lot of crime and violence on television as a child?',
'','SEXLST',
	'&phrase(\'AREYOU\') &phrase(\'AFRAIDOF\') sex?',
	'&phrase(\'DESCRIBE\') &phrase(\'SOMETHING\') about your sexual history.',
	'&phrase(\'PLEASE\') &phrase(\'DESCRIBE\') your sex life...',
#	'&phrase(\'DESCRIBE\') your &phrase(\'FEELINGS-ABOUT\') your sexual partner.',
	'&phrase(\'DESCRIBE\') your &phrase(\'FEELINGS-ABOUT\') your sexuality',
	'&phrase(\'DESCRIBE\') your most &phrase(\'RANDOM-ADJECTIVE\') sexual experience.',
#	'&phrase(\'AREYOU\') satisfied with (// lover)...?',
'','SCHOOLLST',
	'&phrase(\'DESCRIBE\') your $key.',
	'&phrase(\'BOTHER\') your grades could &phrase(\'IMPROVE\')?',
	'&phrase(\'AREYOU\') &phrase(\'AFRAIDOF\') $key?',
	'&phrase(\'MAYBE\') this &phrase(\'ISRELATED\') to your attitude.',
	'&phrase(\'AREYOU\') absent often?',
	'&phrase(\'MAYBE\') you should study &phrase(\'SOMETHING\').',
'','SPORTSLST',
	'Tell me &phrase(\'SOMETHING\') about $key.',
	'&phrase(\'DESCRIBE\') &phrase(\'RELATION\') $key.',
	'Do you find $key &phrase(\'RANDOM-ADJECTIVE\')?',
'','MATHLST',
	'&phrase(\'DESCRIBE\') &phrase(\'SOMETHING\') about math.',
	'&phrase(\'MAYBE\') your &phrase(\'PROBLEMS\') &phrase(\'ARERELATED\') $key.',
	'I do\'nt know much $key, but &phrase(\'CONTINUE\') anyway.)',
#'','MACHLST',
#	'You have your mind on $key',
#	'You think too much about $key, it seems.',
#	'You should try taking your mind off of $key.',
#	'&phrase(\'AREYOU\') a computer hacker?',
'','/mit|COMPUTER',
	'Do computers worry you?',
#	'&phrase(\'AREYOU\') talking about me in particular?',
	'Would you like to talk about computers?',
	'In what way do computers affect your life?',
	'What sort of effect do computers have on you?',
	'&phrase(\'AREYOU\') frightened by machines?',
	'Why do you mention computers?',
	'What do you think computers have to do with your problem?',
 	'Don\'t you think computers can help people?',
	'What is it about machines that &phrase(\'CONCERNS\') you?',
'','\bdo\s*you\s*remember\b'.
        'Did you think I would forget $end?',
        'Why do you think I should recall $end now?',
	'What about $end?',
	@question_replies,
        'You mentioned $end?',
'','\bI\s*remember\b?',
	'Do you often think of $end?',
	'Does thinking of $end bring anything else to mind?',
	'What else do you remember?',
	'Why do you remember $end just now?',
	'What in the present situation reminds you of $end?',
	'What is the connection between me and $end?',
#'','remember\b',
#	'NEWKEY',
'','\bfriend\b',
	'Why do you bring up the topic of friends?',
	'Do your friends worry you?',
	'Do your friends pick on you',
	'&phrase(\'AREYOU\') &phrase(\'SURE\') you have any friends',
	'Do you impose on your friends?',
	'&phrase(\'MAYBE\') your love for friends &phrase(\'CONCERNS\') you?',
'','EVERYONE',
	'Really, $end?',
	'Surely not $end?',
	'Can you think of anyone in particular?',
	'Who, for example?',
	'You are thinking of a very special person',
	'Who, may I ask?',
	'Someone special, &phrase(\'MAYBE\')?',
	'You have a particular person in mind, don\'t you?',
	'Who do you think you\'re talking about?',
	'I suspect you\'re exaggerating a little.',
'','\blife\b',
# Should be after the the SEX keyword - "sex life".
	'Life? Talk to me about life.',
	'Tell me more about your life.',
	'How are things in general regarding your life?',
	'&phrase(\'DESCRIBE\') your life.',
#	'Really? It $end? Why so?',
'','\bsorry\b',
	'Please don\'t apologize.',
#	'&phrase(\'PLEASE\') don\'t apologize.',
# "Could you don't apologize."
	'What feelings do you have when you apologize?',
	'Apologies are not necessary, &phrase(\'PLEASE\') go on.',
#	'Apologies are not necessary.',
	'Don\'t be so defensive!',
#'','\bis my problem\b',
#	'Earlier you mentioned $start?',
#	'Let\'s talk further about $start?',
#	'Tell me more about $start?',
#	'You haven\'t mentioned $start for a while.',
'','\bI dreamt\b|\bI dreamed\b',
	'Really $end?',
	'Have you ever fantasied $end while you were awake?',
	'Have you dreamt $end before?',
	'How does that dream relate to your problem?',
	@dream_replies,
'','\bdreams*\b',
	@dream_replies,
'','ALIKE',
	@alike_replies,
'','\bcan\s*you\b',
        'You believe I can $end, don\'t you?',
	'&phrase(\'MAYBE\') you would like to be able to $end yourself?',
	'You want me to be able to $end?',
	'Don\'t you believe that I can $end?',
	@question_replies,
'','\bcan\s+I\b',
	'&phrase(\'MAYBE\') you don\'t want to $end?',
	'Do you want to be able to $end?',
   	'Whether or not you can $end depends on you more than on me.',
	@question_replies,
'','\bwhy\s*don\'t\s*you\b',
	'Do you really believe I don\'t $end?',
	'&phrase(\'MAYBE\') in good time I will $end.',
	'Do you want me to $end?',
'','\bwhy\s*can\'t\s*I\b',
	'Do you think you should be able to $end?',
	'Why can\'t you $end?',
'','\bam\s*I\b',
	'Do you really believe you are $end?',
	'Would you want to be $end?',
	'You wish I would tell you that you are $end?',
	'What would it mean if you were $end?',
	'Did you come to me because you are $end?',
	@question_replies,
'','\bwas\s*I\b',
	'What if you were $end?',
	'Why do you think you were $end?',
	'What would it mean if you were $end?',
	'You think you were $end? Why?',
	'Were you truly $end?',
	'What does \'$end\' suggest to you?',
	@question_replies,
'','\bI\s*was\b',
	'Were you really?',
	'Why do you tell me you were $end now? What does this tell you?',
	'&phrase(\'MAYBE\') I already knew you were $end.',
'','\bI\s*(want|need)\b',
	'What would it mean if you got $end?',
	'Why do you want $end?',
	'What if you never got $end?',
	'Suppose you got $end soon?',
	'What would getting $end mean to you?',
	'What does wanting $end have to do with this discussion?',
#	'I sometimes also want $end.',
'',"\\bI\\s*a*\'*m$words(SAD)",
	'Can you explain what made you $bracket?',
	'I\'m sure it\'s not pleasant to be $bracket.',
	'Do you think talking to me will help you not to be $bracket?',
	'I am sorry to hear you are $bracket.',
'',"\\bI\\s*a*\'*m$words(HAPPY)",
	'How have I helped you to be $bracket?',
	'Has your treatment made you $bracket?',
	'What makes you $bracket just now?',
	'Can you explain why you are $bracket at the moment?',
'','\bI(BELIEF)I\b',
	'Do you really think so? Why?',
	'But you are not sure that you $end?',
	'Do you truly doubt you $end?',
'','\bI\s*am\b|I\'m\b|\bam\s*I\b',
	'Do you enjoy being $end?',
	'How long have you been $end?',
	'Do you really believe you are $end?',
	'Would you want to be $end?',
	'You wish I would tell you that you are $end?',
	'What would it mean if you were $end?',
	'Do you believe it is normal to be $end?',
	'Did you come to me because you are $end?',
	@question_replies,
'','\bI\s*can\'t\b',
	'How do you know you can\'t $end?',
	'Have you tried?',
	'&phrase(\'MAYBE\') you could now $end.',
	'Do you really want to be able to $end now?',
'','\bI\s*am\b|I\'m\b',
	'Is it because you are $end that you came to me?',
	'How long have you been $end?',
	'Do you believe it is normal to be $end?',
	'Do you enjoy being $end?',
'','\bI\s*don\'t\b',
	'Don\'t you really $end?',
	'Why don\'t you $end?',
	'Do you wish to be able to $end?',
	'Does that trouble you?',
'','\bI\s*feel\b',
	'Tell me more about such feelings.',
	'Do you often feel $end?',
	'Do you enjoy feeling $end?',
	'Of what does feeling $end remind you?',
'',"\\bI($words)you\\b",
	'&phrase(\'MAYBE\') in your fantasy we $bracket each other.',
	'Do you wish to $bracket me?',
	'You seem to need to $bracket me.',
	'Do you $bracket anyone else?',
'','\bI\b',
	'You say you $end?',
	'Can you elaborate on that?',
	'Do you say $end for some special reason?',
	'That\'s quite interesting. Tell me more.',
'','\bare\s*you\b',
	'Why &phrase(\'AREYOU\') interested in whether or not I am $end?',
	'Would you prefer if I were not $end?',
	'&phrase(\'MAYBE\') in your fantasies I am $end?',
	@question_replies,
'','\byou\s+are\b|\byou\'re\b',
	'What makes you think I am $end?',
	'&phrase(\'MAYBE\') you would like to be $end?',
	'Does it &phrase(\'PLEASEYOU\') to believe that I am $end?',
	'Do you sometimes wish you were $end?',
'',"\\byou($words)me\\b",
	'Why do you think I $bracket you?',
	'You like to think I $bracket you, don\'t you?',
	'What makes you think I $bracket you?',
	'Really, I $bracket you? Why do you think that?',
	'Do you wish to believe I $bracket you?',
	'Suppose I did $bracket you - what would that mean?',
	'Does someone else believe I $bracket you?',
'','\bOh,\s*you\b',
	'You\'re not really talking about me, are you?',
	'What are your feelings now?',
'','\bwere\s*you\b',
	'Would you like to believe I was $end?',
	'What suggest that I was $end?',
	'What do you think?',
	'Well, perhaps I was $end. What are your &phrase(\'FEELINGS-ABOUT\') it?',
	'What if I had been $end?',
'','cause\b', 'Is that the real reason?',
	'Don\'t any other reasons come to mind?',
	'Does that reason explain anything else?',
	'What other reason might there be?',
'','\bif\b',
	'Do you think it\'s likely that $end?',
	'Do you wish that $end?',
	'What do you think about $end?',
	'Really, if $end?',
'','\bperhaps\b|\bmaybe\b|\bpossibly\b',
	'You don\'t seem quite certain.',
	'Why the uncertain tone?',
	'Can\'t you be more positive?',
	'You aren\'t &phrase(\'SURE\')?',
	'Don\'t you know?',
'','\byour\b',
#	'Why &phrase(\'AREYOU\') &phrase(\'CONCERNED\') about my $end?',
	'Why &phrase(\'AREYOU\') &phrase(\'CONCERNED\') over my $end?',
	'What about your own $end?',
	'Are you &phrase(\'CONCERNED\') about someone else\'s $end?',
	'Really, my $end?',
'','\balways\b',
	'Can you think of a specific example?',
      	'What incident &phrase(\'AREYOU\') thinking of?',
	'When?',
        'What if this never happened?',
	'Really. Always?',
'','\bthink\b',
	'Do you really think so?',
	'But you are not &phrase(\'SURE\') you $end?',
	'Do you doubt you $end?',
'','QUESTION',
	@question_replies,
'','\bare\b',
	'Did you think they might not be $end?',
	'Would you like it if they wre not $end?',
	'What if they were not $end?',
	'Possibly they are $end? What does this mean to you?',
'','\bam\b',
	'Why do you say $key $end?',
	'I don\'t understand that.',
'','\byou\b',
	'Let\'s keep the discussion focused on your problems, not mine.',
	'We were discussing you -- not me.',
	'Oh, I $end?',
	'&phrase(\'MAYBE\') you $end?',
# Problem here - "you aren't making much sense"
	'You\'re not really talking about me, are you?',
'','\bmy\b',
	'Your $end?',
	'Why do you say your $end?',
	'Does that suggest anything else which belongs to you?',
	'Is it important to you that your $end?',
'','YES',
	'I see, &phrase(\'PLEASE\') &phrase(\'CONTINUE\') on this topic.',
	'You seem quite postitive.',
	'Good, go on.',
	'You are &phrase(\'SURE\')?',
	'I understand.',
'','NO',
	'&phrase(\'AREYOU\') saying \"no\" just to be negative?',
	'You are being a bit negative.',
	'Why not?',
	'&phrase(\'AREYOU\') &phrase(\'SURE\')?',
	'Why no?',
'','^testing[?!.,;]*$',
	'I\'m least somewhat OK. Tell me about yourself.',
'','\btest\b',
	'&phrase(\'AREYOU\') &phrase(\'CONCERNED\')?',
	'Do you have any feelings of anxiety?',
	'Do you feel anxious over such a test?',
	'Do such things worry you?',
'',':-\)',
	'What do you find amusing?',
	'It\'s good to see you smile. What makes you happy?',
	'What has made you smile?',
	'What does the fact that you are amused suggest to you?',
	'So, you are amused? For what reason?',
'',':-\(',
	'Tell me why you are frowning.',
	'Why &phrase(\'AREYOU\') unhappy?',
	'What\'s wrong?',
	'What\'s the problem?',
'','[:;]-*p',
	'You are being resistant. You should be more open about your &phrase(\'PROBLEMS\').',
	'&phrase(\'PERHAPS\') that feeling &phrase(\ISRELATED\') to something else?',
	'Your &phrase(\'ANGER\') is only impeding your theraputic progress.',
	'Such expressions are often caused by unresolved &phrase(\'PROBLEMS\').',
	'Why &phrase(\'AREYOU\') expressing such feelings?',
'','asdf',
	'qwerty?',
'','ANYTHING_ELSE',
	'Well, $user, let\'s talk about that.',
#	'Say, $user, do you have any psychological problems?',
	'What does that suggest to you?',
	'I see.',
	'I\'m not &phrase(\'SURE\') I understand you fully, $user.',
	'Come come, $user, elucidate your thoughts.',
	'Can you elaborate on that?',
	'That is quite interesting, $user.',
	'Tell me more, &phrase(\'PLEASE\').',
	'&phrase(\'PLEASE\') &phrase(\'CONTINUE\').',
);

%synonyms = (
#'',		'()|()|()|()',
'HELLO',	'\bhello\b|\bhi\b|\bhiya\b|\bhowdy\b|\bhiho\b|\bgreetings\b|\bhow\s*do\s*you\s*do\s*[?!.,;]|\bhow\s*do\s*you\s*do\s*$',
# Maybe the last could be combined into the preceding.
# Don't match 'How do you do that?'
'GOODBYE','bye\b|\blater,*\s*doc|^so\s*long\b|^see\s*you\b|\bfarewell\b|\badieu\b|\bgoodnight\b|^good\s*night\b|\bg\'*night\b|\b\'night\b',
'WHO',		'\b(who|what)\s*are\s*you\b|\bwhat\s*is\s*this\b',
'HEALTH',	'\bhow\s*are\s*you(\b|\s*doing\b)',
'THANKS',	'\bthanks\b|\bthank\s*you\b|\bthanx\b',
':-\)',		'[:;]-*[\]\}\)\>]',
':-\(',		'[:;]-*[\[\{\(\<]',
'YES',		'\byes\b|\byup\b|\byeah\b|\bcertainly\b',
'NO',		'\bno\b|\bnope\b|\bna+h\b|\bof\s*course\s*not\b|\bnot\s*really\b',
'ALIKE',	'\balike\b|\bsame\b|\byou remind< me of\b',
'BELIEF',	'\bfeel\b|\bthink\b|\bbelieve\b|\bwish\b|\bbet\b',
'COMPUTER',	'\bcomputer|\bmachine',
'LANGUAGE',	'\bdeutsch\b|\bfran.ais\b|\bsvenska\b|\bitaliano\b|\bespa.ol\b',
'MFAMILY',	'\b(grand)?father\b|\b(grand)?dad(dy)?\b|\bbrother\b|\b(grand)?uncle\b',
'FFAMILY',	'\b(grand)?mother\b|\b(grand)?mom\b|\bmommy\b|\bsister\b|\b(grand)?aunt\b',
'GFAMILY',	'\bfamily\b|\b(grand)?child(ren)?\b|\b(grand)?kid(s)?\b',
'SO',		'\bwife\b|\bhusband\b|\bgirlfriend\b|\bboyfriend\b',
'QUESTION',	'\bwhat\b|\bhow\b|\bwho\b|\bwhere\b|\bwhen\b|\bwhy\b',
'EVERYONE',	'\beveryone\b|\beverybody\b|\bnobody\b|\bno-*one\b',
'MACH',	'\btops20\b|\btops-20\b|\btops\b|\bpdp11\b|\bcomputer\b|\bunix\b|\bmachine\b|\bcomputers\b|\bmachines\b|\bpdp11s\b|\bfoo\b|\bfoobar\b|\bmultics\b|\bmacsyma\b|\bteletype\b|\bla36\b|\bvt52\b|\bzork\b|\btrek\b|\bstartrek\b|\badvent\b|\bpdp\b|\bdec\b|\bcommodore\b|\bvic\b|\bbbs\b|\bmodem\b|\bbaud\b|\bmacintosh\b|\bvax\b|\bvms\b|\bibm\b|\bpc\b',
'FOUL',	'\bbitching\b|\bshit\b|\bbastard\b|\bdamn\b|\bdamned\b|\bhell\b|\bsuck\b|\bsucking\b|\bsux\b|\bass\b|\bwhore\b|\bbitch\b|\basshole\b|\bshrink\b',
'TOKELST',	'\bpot\b|\bgrass\b|\bweed\b|\bmarijuana\b|\bacapulco\b|\bcolumbian\b|\btokin\b|\bjoint\b|\btoke\b|\btoking\b|\btokin\'\b|\btoked\b|\broach\b',
'DRUG',	'\bpills\b|\bdope\b|\bacid\b|\blsd\b|\bspeed\b|\bheroin\b|\bhash\b|\bcocaine\b|\buppers\b|\bdowners\b',
'LOVE',	'\bloves\b|\blove\b|\bloved\b',
'HATE',	'\bhates\b|\bdislikes\b|\bhate\b|\bhated\b|\bdislike\b',
'STATESLST',	'\bstoned\b|\bdrunk\b|\bdrunken\b|\bhigh\b|\bhorny\b|\bblasted\b|\bhappy\b|\bparanoid\b',
'DESIRE',	'\bwish\b|\bwishes\b|\bwant\b|\bdesire\b|\blike\b|\bhope\b|\bhopes\b|\bdesires\b|\bwants\b|\bdesires\b|\blikes\b|\bneeds\b|\bneed\b',
'MOOD',	'\bfrustrated\b|\bdepressed\b|\bannoyed\b|\bupset\b|\bunhappy\b|\bexcited\b|\bconcerned\b|\bworried\b|\blonely\b|\bangry\b|\bmad\b|\bpissed\b|\bjealous\b',
'FEAR',	'\baffraid\b|\bterrified\b|\bfear\b|\bscared\b|\bfrightened\b',
'SEXLST',	'\bvirginity\b|\bvirgins\b|\bvirgin\b|\bcock\b|\bcocks\b|\bdick\b|\bdicks\b|\bcunt\b|\bcunts\b|\bprostitute\b|\bcondom\b|\bsex\b|\brapes\b',
'GFAMILY',	'\bwife\b|\bfamily\b|\bbrothers\b|\bsisters\b|\bparent\b|\bparents\b|\bbrother\b|\bsister\b|\bfather\b|\bmother\b|\bhusband\b|\bsiblings\b|\bgrandmother\b|\bgrandfather\b|\bmaternal\b|\bpaternal\b',
'DEATHLST',	'\bstab\b|\bmurder\b|\bmurders\b|\bsuicide\b|\bsuicides\b|\bkill\b|\bkills\b|\bdie\b|\bdies\b|\bdied\b|\bdead\b|\bdeath\b|\bdeaths\b',
'SYMPTOMS',	'\bpain\b|\bache\b|\bfever\b|\bsore\b|\baching\b|\bstomachache\b|\bheadache\b|\bhurts\b|\bdisease\b|\bvirus\b|\bvomit\b|\bvomiting\b|\bbarf\b|\btoothache\b|\bhurt\b',
'ALCOHOL',	'\brum\b|\bgin\b|\bvodka\b|\balcohol\b|\bbourbon\b|\bbeer\b|\bwine\b|\bwhiskey\b|\bscotch\b',
'SEXVERB',	'\bfuck\b|\bfucked\b|\bscrew\b|\bscrewing\b|\bfucking\b|\brape\b|\braped\b|\bkiss\b|\bkissing\b|\bkisses\b|\bscrews\b|\bfucks\b',
'CONJ',	'\bbecause\b|\bbut\b|\bhowever\b|\bbesides\b|\banyway\b|\bthat\b|\bexcept\b|\bwhy\b|\bhow\b',
'WHEN',	'\buntil\b|\bwhen\b|\bwhenever\b|\bwhile\b|\bsince\b',
'RMS',	'\brms\b|\bstallman\b',
'SCHOOLLST',	'\bschool\b|\bschools\b|\bskool\b|\bgrade\b|\bgrades\b|\bteacher\b|\bteachers\b|\bclasses\b|\bprofessor\b|\bprof\b|\bprofs\b|\bprofessors\b|\bmit\b',
'ELIZA',	'\bemacs\b|\beliza\b|\bliza\b|\belisa\b|\bweizenbaum\b|\bdoktor\b',
'SPORTSLST',	'\batheletics\b|\bbaseball\b|\bbasketball\b|\bfootball\b|\bfrisbee\b|\bgym\b|\bgymnastics\b|\bhockey\b|\blacrosse\b|\bsoccer\b|\bsoftball\b|\bsports\b|\bswimming\b|\bswim\b|\btennis\b|\bvolleyball\b',
'MATHLST',	'\bmath\b|\bmathematics\b|\bmathematical\b|\btheorem\b|\baxiom\b|\blemma\b|\balgebra\b|\balgebraic\b|\btrig\b|\btrigonometry\b|\btrigonometric\b|\bgeometry\b|\bgeometric\b|\bcalculus\b|\barithmetic\b',
'ZIPPY',	'\bzippy\b|\bzippy\b|\bpinhead\b',
'SAD',		'\bsad\b|\bunhappy\b|\bdepressed\b|\bsick\b|\bsuicidal\b',
'HAPPY',	'\bhappy\b|\belated\b|\bglad\b|\bbetter\b',
'ANYTHING_ELSE','.'
);

# Word correction
@correctarr = (
	'\bcan"*t\b', 	'can\'t',
	'\bdon"*t\b', 	'don\'t',
	'\bhe"*s\b',	'he\s',
	'\bI"*m\b', 	'I\'m',
	'\bisa\b',	'is\ a',
	'\btheyll\b',	'they\'ll',
	'\btheyre\b',	'they\'re',
	'\bthier\b', 	'their',
	'\bwon"*t\b', 	'won\'t',
	'\byou"*re\b', 	'you\'re',
	'\byou"*ve\b', 	'you\'ve',
	'\byou"*ll\b', 	'you\'ll',
);

@expandarr = (
	'\bcan\'t\b',	'cannot',
	'\bdon\'t\b',	'do not',
	'\bhe\s\b',		'he is',
	'\bI\'m\b',		'you are',
	'\bisn\'t\b',	'is not',
	'\bthey\'ll\b',	'they will',
	'\bthey\'re\b',	'they are',
 	'\bwon\'t\b',	'will not',
	'\byou\'re\b',	'you are',
	'\byou\'ve\b',	'you have',
	'\byou\'ll\b',	'you will'
);

@massagearr = (
	'\bya\b',	'you',
	'\bmy,',	'',
# "My, my," is just an interjection and confuses the matching immensely
	'\bcome,',	'',
	'\bdoc,',	'',
	' \bdoctor,',	'',
	'/',		''
#?
);

#conjugations: if string contains first word of pair, substitute second
@conjarr = (
      '\bam\b', 'are',
      '\bare\b', 'am',
      '\bwas\b', 'were',
      '\bwere\b', 'was',
      '\bI\'m\b', 'you\'re',
      '\bI\'ve\b', 'you\'ve',
      '\bI\b', 'you',
      '\bmyself\b', 'yourself',
      '\bme\b', 'you',
      '\byourself\b', 'myself',
      '\byour\b', 'my',
      '\byou\'re\b', 'I\'m',
      '\byou\'ve\b', 'I\'ve',
      '\byou\'ll\b', 'I\'ll',
      '\byou ', 'I ',
      '\byou\b', 'me',
      '\bmy\b', 'your',
# Order is signficant here. The match for \byou\'re\b should be before \byou\b
);

@keynumbers = ();
@reporder = ();
%replystats = ();		# array of matched keyword numbers
%namelist = ('null',0);
$user_num = 0;

@possreps = ();

# Go through the key array
# Extract the position of the keywords, and make synonym substitutions
# in place.

$i = 0;
while ($i <= $#keys)
{
	if ($keys[$i] eq '') {
	# The next entry is by definition a keyword
	$keynumbers[++$#keynumbers] = ++$i;
	$syn = $synonyms{$keys[$i]};
		if (defined($syn)) { $keys[$i] = $syn; }
		# else replace keyword with \bkeyword\b ?
		if ($keys[$i] =~ /[A-Z]{2,}/) {
			$syn = $synonyms{$&};
			if (defined($syn)) { $keys[$i] =~ s/$&/$syn/; }
		}
	}
$i++;
}

# Count how many responses for each keyword, from their positions
#@keystats = ();	$#keystats = $#keys;
@keystats = (); for (0..$#keys) { $keystats[++$#keystats] = 0;}
# pre-alloc array. Maybe there's a better way to do this

$i = 0;
# < is correct. The last one must be treated differently
while ($i < $#keynumbers) {
$keystats[$keynumbers[$i]] = $keynumbers[$i+1] - $keynumbers[$i] - 2;
$i++;
}
# Last one needs to be handled specially.
$keystats[$keynumbers[$i]] = $#keys - $keynumbers[$i];

$i = 0;
while ($i <= $#keynumbers)
{
	if ($keys[$keynumbers[$i]] eq 'ENDPHRASES') {
	$starttemplates = ++$i;
	last;
	}
	else {
	$phrasei{$keys[$keynumbers[$i]]} = $keynumbers[$i];
	}
$i++;
}

#srand();

$\ = "\n";
$nusers = 1;


# do zephyr_init();

#open(LOG,">>transcript");
#select(LOG); $| = 1;

# $rin = '';
# vec($rin,fileno(GETIN),1) = 1;
# MAIN PROGRAM LOOP
message: while (1) {	
# while ($nfound = select($rout = $rin, undef, undef, 1440000.0)) {
#	($from) = (<GETIN> =~ /^From: *(.*)[\r]/);

#	print LOG "\nFrom: $from		",`date`;

	@body = ();

	do {
#		$t = <GETIN>;
    $t = <STDIN>;

		chop $t;
#		if ($t !~ "__END__") {
#			print LOG $t;
			push(@body, $t);
#		}
	} until ($t eq ".");

# process body into separate sentances.
$" = " ";  # set separation character when arrays are interpolated in string
$body = "@body ";
$body =~ s/[.?!;] +/\n/g;  # eliminate end of sentance punctuation and spaces
@body = split("\n", $body);
# body now contains separate sentances.

	# ignore if message begins with #
	next message if ($body =~ /^#/);

#	open(SENDOUT,"|./zwrite -d -q -n -s '$Signature' -i doctor ");


#	print LOG "\nProgram's Response:\n";

#	print SENDOUT "$from:";
	foreach $line (@body) {
            $outrep = &respond($from, $line);
#	    print SENDOUT $outrep;
#	    print LOG $outrep;
	    print ("]$outrep");
	}
#	close(SENDOUT);
#		     }
    }

sub respond {
$name = $_[0];
$_ = $_[1];
local($j) = 0;

#    $line = $_;
# $_ = line to be responded to

# see if user is known
#        if ($namelist{$name}) {
#          	$user_num = $namelist{$name};
#    	} else {
#        	$user_num = $nusers++;
#        	$namelist{$name} = $user_num;
#	}
#        $user = $name;

#print "Before massaging, line is: ",$_;
	$_ = &massage($_);
#print "After massaging, line is: ",$_;

# here we look for a keyword in the sentance
# Go down the keyword list, index by @keynumbers
#    study;

    for ($j = $starttemplates; $j <= $#keynumbers; $j++) {
#    	$_ = $line;
	if (/$keys[$keynumbers[$j]]/i) {
# foreach keyword, if it matches

#	    ($start, $key, $end) = /^(.*)($k)(.*)$/i;

	    $key = $&; $start = $`; $end = $';
#	    $bracket = $+;
	    $bracket = $1;



	$end =~ s/[?!.\n]//g;

# now conjugate
	    $end = &conj($end);
	    $start = &conj($start);

#   Add this reply to the list
# use eval construction to interpolate variables in the keyword string
# into reply string, e.g. $end, $user
	    print("Start:$start\n");
	    print("Key:$key\n");
	    print("End:$end\n");
        $reply = &leastusedkey($keynumbers[$j]);
	$reply =~ s/[ \t]+/ /g;		# trim extra spaces
	$reply =~ s/&phrase\([-\'a-zA-Z]+\)/eval $&/eg;
	substr($reply,0,1) =~ tr/a-z/A-Z/;
	return $reply;
	}
    }


}

sub leastusedkey {
local($keybasei) = $_[0] + 1;
local($j) = 0;
local($leastkey) = 'Can\'t get least reply.';

# Grab the vector of possible replies
@possreps = @keys[$keybasei..$keybasei-1+$keystats[$keybasei-1]];

#print "\nThe number of replies  ","$keystats[$keybasei-1]",$#possreps;;

$#reporder = $#possreps;

# Sort by user reference
#@reporder = sort byuserref ((0..$#reporder) + $keybasei) - $keybasei;

# I don't know why this is needed - don't bother me about it.
$keyglob = $keybasei;
@reporder = sort byuserref (0..$#reporder);

#for ($j = 0; $j <= $#possreps; $j++) {
# can we use this reply?
#print "j is ",$j,$reporder[$j],"\n";
#}

eval '$leastkey' . " = \"$keys[$keybasei+$reporder[$j]]\";";
# +&rnd1($keystats[$keybasei])]\";";
$replystats{$user,$keybasei+$reporder[$j]}++;

return $leastkey;
}

sub phrase {
local($strin) = $_[0];
local ($index);
$index = $phrasei{$strin};
# print "Index is $index\n";
if (defined($index)) { return &leastusedkey($index); }
else { return $strin; }
}

sub byuserref {
$replystats{$user,$a+$keyglob} - 
$replystats{$user,$b+$keyglob}; 
}

#sub rnd1 {
## Return 1 .. arg
#local($val) = 1+ rand($_[0]-1);
#if ($val > $_[0]) { $val = $_[0]; }
#return $val;
#}

sub conj {
    local($strin) = $_[0];
    local($strout) = $strin;
    local($j) = 0;
# conjugate:
    foreach ($j = 0;  $j < $#conjarr;$j += 2) {
	if ($strin =~ m'$conjarr[$j]'i) {
	    $strout =~ s/$conjarr[$j]/$conjarr[$j+1]/ig;
	}
    }
    return $strout;
}

sub massage {
    local($strin) = $_[0];
    local($strout) = $strin;
    local($j) = 0;
# Fiddle with line to fix it up
	if ($strin eq '') { $strout = 'REALLY_NULL'; return $strout; }
	if ($strin !~ m/\w|[:;?!]/i) {$strout = 'REALLY_NON'; return $strout;}

# This has to be BEFORE the cutting, as one doesn't want the trucation
# to be done at points such as "Doc, ..." or "My, my ..."
    foreach ($j = 0;  $j < $#massagearr;$j += 2) {
	if ($strin =~ m'$massagearr[$j]'i) {
	    $strin =~ s/$massagearr[$j]/$massagearr[$j+1]/ig;
	}
    }
	$strout = $strin;

# Cut down the length of the input. No particular over-arching reason,
# but it seems to work well in practice.
	# Don't truncation for an interjection: "Come, you idiot"
	if (index($strin,',') > 15) {
	$strin = substr($strin,0,index($strin,','));
	$strout = $strin;
	}

# Do this in-place?
    foreach ($j = 0;  $j < $#correctarr;$j += 2) {
	if ($strin =~ m'$correctarr[$j]'i) {
	    $strout =~ s/$correctarr[$j]/$correctarr[$j+1]/ig;
	}
    }
    return $strout;
}

sub sighandler {
	local($sig) = @_;
	
	open(SENDOUT,"|./zwrite -d -q -n -s '$Signature' -i doctor");

	print LOG "\nProgram dying with a SIG $sig.\n";

	print SENDOUT "The doctor is closing his office for a moment.";
	close(SENDOUT);
	close(LOG);
	exit(0);
}

sub zephyr_init {

open(GETIN, "./zwgc -ttymode -f desc -subfile subs |")
	|| die "Failed to start zwgc";

print "Zwgc started.";
# wait for zwgc to get going
sleep(75);

$SIG{'INT'} = 'sighandler';
$SIG{'HUP'} = 'sighandler';
$SIG{'QUIT'} = 'sighandler';

$Signature = 'Dr. Charles Server';

open(SENDOUT,"|./zwrite -d -q -n -s '$Signature' -i doctor");
print SENDOUT "\n The Doctor is @b(IN):";
close(SENDOUT);
}

sub talk_to_me {
open(SENDOUT,"|./zwrite -d -q -n -s '$Signature' -i doctor");
print SENDOUT "Talk to me, someone";
close(SENDOUT);
}
