/*

  This is a part of the Project Frontier's Source code.

  Copyright (C) 1997-98 Francis Gastellu
                    aka Lone Runner/Aegis

  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 General 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., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

*/

/*

Additionnal comm related functions

*/


#include <conio.h>
#include <dos.h>
#include <stdlib.h>
#include <string.h>
#include <alloc.h>
#include "..\com\system.h"
#include "..\com\rs232.h"
#include "..\com\async2.h"
#include "..\com\pcbdat.h"

char *inBuf=NULL, *outBuf=NULL;
int initCode=0;


int comInit(void)
{
int port=0;
int localMode=0;

	if (!strncmpi(comPort, "COM", 3))
		{
        port = comPort[3];
        if (port < '1' || port > '4')
        	{
            rs_user.irq = comIrq;
            rs_user.base = comBase;
            port = '0';
            }
	    }
    else if (strcmpi(comPort, "NONE"))
        localMode = 1;
    else
    	{
        localMode = 1;
    	return -8;
        }

if (!localMode)
	{
    if (!inBuf) inBuf = (char *)malloc(4096);
    if (!outBuf) outBuf = (char *)malloc(4096);
    initCode = rs_initport(port, initialPortSpeed, 'N', '8', '1', 4096, inBuf, 4096, outBuf);
    rs_modctrl(RS_WRTMCR,RS_MCRDTR | RS_MCRRTS,RS_LINON);
    delay(10);
    rs_clrout();
    rs_clrin();
    }
else
	initCode = 1;

return initCode;
}

char AsyncGet(void)
{
char a;
a = disableHiAsciiFilter != 0 ? rs_getbyt() : rs_getbyt() & 0x7F;
if (a == 10) a = disableHiAsciiFilter != 0 ? rs_getbyt() : rs_getbyt() & 0x7F;
if (a != -1) lastKey = *(long*)0x0040006CL;
return a == -1 ? 0 : a;
}

void AsyncPut(char c)
{
int a=-1;

if (initCode <= 0)
	return;

while(a==-1)
	{
	if (disableHiAsciiFilter != 0)
		a = rs_sndbyt(c);
	else
		a = rs_sndbyt(c & 0x7F);
    checkCarrier();
    }
}

void AsyncPutStr(char *str)
{
int a;

for (a=0;a<strlen(str);a++)
	AsyncPut(str[a]);
}

int Carrier(void)
{
return((rs_modctrl(RS_GETMSR) & RS_DCDSTE) != 0);
}

int InStat(void)
{
if (initCode <= 0)
	return 0;
return rs_inrcvd();
}

int OutStat(void)
{
if (initCode <= 0)
	return 0;
return (4096 - rs_outfre());
}

void checkCarrier(void)
{
static inUse=0;

if (initCode <= 0 || carrierSpeed == 0 || !CDchecking) return;

if (!Carrier() && !inUse)
	{
    inUse = 1;
	runSystemPPE("CARRLOST.PPE");
    inUse = 0;
    initCode=0;
    }
}

void AsyncClose(void)
{
rs_modctrl(RS_WRTMCR,RS_MCRDTR | RS_MCRRTS,RS_LINOFF);
rs_close();
initCode=0;
}
