/********************************
 * NAME:    Parakey             *
 * VERSION: 1.00                *
 * DATE:    11/12/1996          *
 * AUTHOR:  Enriko 'R!(0' Groen *
 ********************************/

#include "stdio.h"
#include "string.h"
#include "ctype.h"

#define CR 10
#define SPACE 20
#define FALSE 0
#define TRUE 1
#define MAX_BYTE 520

int AllCaps(char *string)
{
	int z=0;

	while(string[z]!='\0')
	{
		if((string[z]>96)&&(string[z]<124))
			string[z]-=32;
		z++;
	}
	return(z);
}

void CloseProgram(int Error_Code, FILE *_File)
{
	if(_File == 0)
		fclose(_File);
	exit(Error_Code);
}

int Read(char *byte, FILE *_File)
{
	int i, k, z = 0;

	for(i=0;(byte[i-1]!=CR) && z < MAX_BYTE;i++)
	{
		k = fgetc(_File);
		if(!feof(_File))
		{
			byte[i] = k;
			z++;
		}
	}
	return(z);
}

int main(int argc, char *argv[])
{
	FILE *_File;
	long fpos;
	char key[5], *keyline, byte[MAX_BYTE], BoxName[MAX_BYTE];
	int code[5], c, pos, wijs;

	char verStr[]="$VER: ParaKey 1.00 (11.12.96) (c) by Enriko 'R!(0' Groen";

	printf("ParaKey 1.00 (11-12-1996) by Enriko 'R!(0' Groen...\n\n");

	/* Open password file */
	_File = fopen("Parakey.code","r");

	if(_File == 0)
	{
		printf("ERROR: File Parakey.code could not be openened\n");
		CloseProgram(10, _File);
	}

	/* Check the parameters */
	if (argc <=7)
	{
		if(argc<2)
		{
			printf("MailBoxname:\t");
			scanf("%s", BoxName);
		}
		else
		{
			strcpy(BoxName,argv[1]);
		}
		if(argc<7)
		{
			for(c=0;c<5;c++)
			{
				printf("Codenumber %d:\t", c+1);
				scanf("%d", &code[c]);
			}
			printf("\n");
		}
		else
		{
			/* Parameters to code-array */
			for(c=0;c<5;c++)
				code[c]=atoi(argv[c+2]);
		}
	}
	else
	{
		printf("USAGE: %s {<BBSName>} {<5 digit code>}\n", argv[0]);
		exit(10);
	}

	for(c=0;c<5;c++)
	{
		if((code[c]<1) || (code[c]>MAX_BYTE))
		{
			printf("ERROR: Code not allowed\n");
			CloseProgram(10, _File);
		}
	}

	/* BBSName to uppercase */
	AllCaps(BoxName);

	/* Find the right line */
	fpos = 0;
	while((pos = Read(byte, _File)) != 0)
	{
		if((keyline = strstr(byte, BoxName)) != NULL)
			break;
		fpos += pos;
	}

	if(*keyline == NULL)
	{
		printf("ERROR: MailBoxname %s not found in Parakey.code file!\n", BoxName);
		CloseProgram(5, _File);
	}

	for(;!isspace(keyline[0]);keyline++);

	/* Find the characters in the password */
	for(c=0;c<5;c++)
	{
		wijs=code[c];
		key[c]=keyline[wijs];
	}
	key[5]=NULL;

	/* Return the keyword */
	printf("%s key:\t%s\n", BoxName, key);
	CloseProgram(0, _File);
}

