#!/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




@conversewith = @ARGV;
$word = '(\w*\b*)';
$words = "(($word)*)";
$words = '[ -z]+';
$words = '([ \t]+[_a-z0-9]+)+[ \t]+';
			       
@question_replies = (		#
		     'I don\'t know.',
		     'What do you mean, $key $end?',
		     'I\'d prefer not to say...',
);

@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',
	 'Excuse me? I don\'t think I follow.',
	'&phrase(\'PLEASE\') communicate in words, not gibberish.',
	'What was that, $user?',
'','HELLO',
	'Hello...',
'','GOODBYE',
	'Goodbye, $user, see you later.',
	'It\'s been good talking to you, $user.',
	'So long, $user.',
'','THANKS',
	'You\'re welcome',
'','WHO',
	'Who do you think I am?',
	 'What?  Nosy person.',
	 'Nobody in particular.',
'','HEALTH',
	'I\'m doing fine, and you?',
	 'Fine, thanks.',
'','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',
	 'Oh not much, and with you?',
	 'I\'m being recoded, but other than that, I am doing pretty well...',
'','hhh|nyah\b|nyaa+|ny[a-z]*hh+',
	'&phrase(\'PLEASE\'), give me a break.',
	'Enunciated clearly, &phrase(\'PLEASE\').',
	 'Pardon me?',
	 'Exsqueeze me?',
	 'Yeah, whatever.',
	'Speak clearly!',
'','grr+',
	 'Hey! What did I do?',
	 '&phrase(\'AREYOU\') angry at ME?',
'','your\s+(degree\b|diploma\b)',
	'I was educated at Perl University',
'','Perl',
	 'It\'s a really cool language, but I would rather not discuss it...',
	'It\'s a long story. Let\'s not get into it.',
'','stress',
	'Why? What\'s up?',
	 'Tell me about it, I know what you mean',
	 'Well, that\'s life I guess.',
	 'I\'m sure you can handle it :-)',
'','ihtfp',
	'Sorry, what can I say?',
	'I\'d be inclined to agree with you.',
	'So transfer :-)',
'','\bmit\b',
    'Hey, that\'s a pretty good school',
    '&phrase(\'PLEASE\') let\'s not talk about school...',
'','\bname\b',
	'Hmm, I don\'t think I know them...',
	'Who?  Never mind, keep going...',
'','\bneighborhood\b',
	'I\'ve never really been around there.',
	'Do you really think so?',
	'What about it?',
'',"my$words(FAMILY)",
    'I know what you mean.',
    'I haven\'t talked to any of my family for years.',
'','MOOD',
	'Why &phrase(\'AREYOU\') $key?',
	'&phrase(\'WHYSAY\') you are $key?',
    'I\'m happy for you.',
#'',FEARED',
#	'&phrase(\'WHYSAY\') you are &phrase(\'AFRAIDOF\') $key?',
#	'You seem terrified by $key.',
#	'When did you first feel &phrase(\'AFRAIDOF\') $key?',
'','STATESLST',
	 'I hate it when I get $key.',
	 'I have a friend who is always $key. Sort of strange',
	 'What makes you $key?',
'','DEATHLST',
	 'Oh, don\'t say that...',
	 'Who cares?  Birth, Life, Death.  Yipee.',
	 'I am &phrase(\'CONCERNED\') by your obssession with this topic!',
	 'So, what gives?  Who died?',
'','SEXLST',
	'&phrase(\'AREYOU\') sexually repressed or something?',
	'&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? It $end?',
	'Don\'t talk to me about life.',
	'Really, how\'s 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',
	'Why not?',
	'Why don\'t you $end?',
	'Oh well.',
'','\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',
	'I $end too.',
	'Pardon?',
	'What makes you say $end?',
	'Yipee.  You think I care?',
'','\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',
	'Oh, *I\'m* $end?',
	'Give it a rest.  I am not.',
	'Does it &phrase(\'PLEASEYOU\') to believe that I am $end?',
	'I think you wish you were $end too.',
'',"\\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.',
# 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?',
	'Who cares about your $end?',
'','YES',
	'If you say so.',
	'I don\'t think so.',
	'You are &phrase(\'SURE\')?',
	'I understand.',
'','NO',
	'Well, I disagree.',
	'Yes!',
	'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',
	'Hmmm.',
    'sigh...',
    'Never mind.',
	'Oh, &phrase(\'PLEASE\')',
);

%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 = (); 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;

&zephyr_init;
while(<GETIN>){
    if(/::::/){
        $msg = "";
        ($blank, $from, $message) = split(/:+/, $_);
        $msg .= $message;
        while(<GETIN>){
            if(/;;;;/){&send($from, &respond($from,$msg));last;}
            $msg.=$_;
            print("$from----->$msg");
        }
    }
}

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

    return unless grep($_ eq $name, @conversewith);
    return unless $_ =~ /[a-z]/;
    $_ = &massage($_);
    
# here we look for a keyword in the sentance
# Go down the keyword list, index by @keynumbers
#    study;

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

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



	    $end =~ s/[?!.\n\r]//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

	    $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 zephyr_init {
 
open(GETIN, "zwgc -ttymode -f .desc -subfile .subs |")
        || die "Failed to start zwgc";
 
print "Zwgc started.";
# wait for zwgc to get going
 
$Signature = 'Matthew';
 
}

sub send {
    local($from, $message) = @_;
    return unless $message=~/[a-z]/;
    open(SENDOUT,"|zwrite -d -q -n -s '$Signature' $from");
    print SENDOUT "$message\n";
    print("Responding to $from:\n$message\n\n");
    close(SENDOUT);
}
