#include <proto/exec.h>
#include <proto/dos.h>
#include <proto/lowlevel.h>
#include <exec/memory.h>
#include <devices/serial.h>
#include <exec/io.h>

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>

#include "filedoor_structs_defines.h"
#include "filedoor_protos.h"

#include "xproto.h"
#include "xpr_lib.h"

/* Prototyper til xprXXXXXX.library */
long __saveds __asm XProtocolSetup(register __a0 struct XPR_IO *xio);
long __saveds __asm XProtocolCleanup(register __a0 struct XPR_IO *xio);

/* Globale variable */
volatile char *vers="$VER:"TITLE;   /* Versionsstreng */
char UserName[50];                  /* Brugernavn */
int accesslevel;                    /* Brugers accesslevel */
struct Areamem *firstarea=NULL;     /* Første area */
struct Areamem *activearea=NULL;    /* Aktive area */
int numareas;                       /* Antal areas ialt */
BOOL showshort=FALSE;               /* Faktisk omvendt - hmm. */
int taggedfiles=0;                  /* Tæller antal filer der er tagget */
LONG availfiles;                    /* Antal files der kan downloades */
LONG downloadedfiles;               /* Antal files der er downloadet */
LONG uploadedfiles;                 /* Ditto uploaded */
LONG ratio;                         /* Hvor meget kan man DL når man har UL én fil?..=ratio */
int visiblelines;                   /* Antal synlige liner - coming up */
char *superarea="AMINET5";          /* Superarea. Patch eller genistreg? */
char line_number;                   /* ASCII '1' eller '2' eller whatever tlf.linie vi er på */
/* Globale variable til XPR */
struct Library *XProtocolBase;      /* Base for vores xpr-library */
struct XPR_IO xprio;                /* Universal io-struct til xpr brug */
struct MsgPort *SerialPort;         /* Serial IO messageport */
struct IOExtSer *SerRequest;        /* Serial IO message */
struct MsgPort *SerialPort2;        /* En til til bi-dir! */
struct IOExtSer *SerRequest2;       /* En til til bi-dir! */
/* Globale variable til at tilgå serielport udenom MAX */
__far char serialname[40]="serial.device";
int serialunit=0;
BOOL bypass=FALSE;
/* Requester kill vha. findtask */
struct Process *proc;

void main(int argc,char *argv[])
{
static __far char buffer[81];
static __far char cportname[12];	    /* ReplyPort and Control Port names */
static __far char temp[100];
BPTR lock;
int i;

	/* Pull out the line number from the argv field to find where we are */
	line_number=argv[argc-1][0];
  /* Get serial.device and unit out of enviromental variable */
  sprintf(buffer,"CydalFileDoorSerial%c",line_number);
  if(GetVar(buffer,temp,40,0L)!=-1)
  {
    for(i=0;temp[i]!=32 && temp[i]!=0;i++);
    temp[i]=0;
    strcpy(serialname,temp);
    serialunit=atoi(temp+i+1);
  }
  /* Get name of the superarea we are using or default aminet5 */
  if(argc==3) superarea=argv[1];
	/* Create the door reply messageport */
	sprintf(buffer,"DoorReply%c",line_number);
	replyport=(struct MsgPort *)CreatePort(buffer,0L);
	doormsg=(struct DoorMsg *)AllocMem((long)sizeof(struct DoorMsg),MEMF_PUBLIC|MEMF_CLEAR);
	if(doormsg==0)
	{
		return;
	}
	doormsg->Door_Msg.mn_Node.ln_Type = NT_MESSAGE;
	doormsg->Door_Msg.mn_ReplyPort = replyport;
	doormsg->Door_Msg.mn_Length = (UWORD)sizeof(struct DoorMsg);
	/* Locate the correct DoorControl port based on the line number */
	sprintf(cportname,"DoorControl%c",line_number);
  Forbid();
 	MyPort=(struct MsgPort *)FindPort(cportname);
  Permit();
 	if(MyPort==0L) 
	{
		FreeMem(doormsg,(long)sizeof(*doormsg));
		return;
	}
  /* Slå alt hvad der hedder requestere fra for os */
  proc=(struct Process *)FindTask(0);
  proc->pr_WindowPtr=(void *)-1L;
  /* Nu kan vi checke om superareaet faktisk eksisterer */
  if(stricmp(superarea,"hdfiles"))
  {
    strcpy(temp,superarea);
    strcat(temp,":");
    if(lock=Lock(temp,ACCESS_READ))
    {
      UnLock(lock);
    }
    else
    {
      msg("\xc"FG1"Not online! Page sysop or write a note..\n");
      AnyKey();
      end();
    }
  }
  /* Byd brugeren velkommen */
  msg("\xc"FG1);
  msg("                                                              ___\n");
  msg("      ____      ____   ____   _______   _______   ________   / _/\\ _______\n");
  msg("     /    \\    /   /\\ /   /\\ /   ___/\\ /   ___/\\ /   ____/\\ /_/ _//   ___/\\\n");
  msg("    /      \\  /   / //   / //   /___\\//   /___\\//   /____\\/// _/ /   /___\\/\n");
  msg("   /   /\\   \\/   / //   / / \\__  \\    \\__  \\   /   ___/\\   \\\\/   \\__  \\\n");
  msg("  /   / /\\      / //   / /____/  /\\ ____/  /\\ /   /___\\/       ____/  /\\\n");
  msg(" /___/ /  \\____/ //___/ //______/ //______/ //_______/\\       /______/ /\n");
  msg(" \\___\\/    \\___\\/ \\___\\/ \\______\\/ \\______\\/ \\_______\\/       \\______\\/\n");
  msg("    ________    ____   ____   __________   __________    __________\n");
  msg("   /_______/\\  /___/\\ /___/\\ /_________/\\ /_________/\\  /_________/\\\n");
  msg("   \\       \\ \\/    \\ \\\\   \\ \\\\    __   \\ \\\\    __   \\|_ \\    __   \\ \\\n");
  msg("    \\    _  \\/      \\ \\\\   \\ \\\\   \\ \\___\\/_\\   \\_\\  |_ \\ \\   \\ \\   \\ \\\n");
  msg("     \\   \\\\_____/\\   \\ \\\\   \\ \\\\   \\  /___/\\\\    __   \\ \\ \\   \\ \\   \\ \\\n");
  msg("      \\   \\ \\     \\   \\ \\\\   \\ \\\\   \\_\\   \\ \\\\   \\ \\   \\ \\ \\   \\_\\   \\ \\\n");
  msg("       \\___\\/      \\___\\/ \\___\\/ \\_________\\/ \\___\\ \\___\\/  \\_________\\/\n");
  msg(FG4"\n                            CD-ROM FILEDOOR\n");
  msg(FG6"                           Locating areas...\n\n");
  msg(FG5"Program:"FG3"Claus Dyring  "FG7"-  ");
  msg(FG5"Ideas+Suggestions:"FG3"Rene Jensen  "FG7"-  ");
  msg(FG5"BBS Logo:"FG3"Soren Jaral");
  getsvar(1,UserName);        /* Hent navnet */
  for(i=0;UserName[i]!=0;i++)
    if(UserName[i]==',' || UserName[i]==' ' || UserName[i]=='/' || UserName[i]==':') UserName[i]='_';
  accesslevel=getivar(1);     /* Hent svinets access level */
  visiblelines=getivar(9)-9;  /* Find antal linier på skærmen der kan vises */
  downloadedfiles=getivar(105);
  uploadedfiles=getivar(104);
  ratio=getivar(101);
  availfiles=uploadedfiles*ratio-downloadedfiles;
  if(!ratio) availfiles=6666;
  FindAreas();                /* Lokaliser areas i cydalskuffen */
  InitAttrs();                /* Hent taggede filer og indstillinger */
  activearea=firstarea;       /* Et sted skal man jo starte */
  msg("\xc");                 /* Slet lige skærmen */
  MoveCrsr(1,1);
  /* Microsoft presents: bypass '95! Chicago version **CANCELED** */
  if(visiblelines>18) visiblelines=18;
  /* Så kan vi køre mainloopet */
  MainLoop();
  /* Ryd op */
  ZapAttrs();                 /* Gem taggede filer og indstillinger på disk og dealloker */
  FreeAreas();                /* Frigør al hukommelse brugt på areas + filer */
  /* Exit */
	end();
}
