
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <exec/types.h>
#include <proto/exec.h>
#include <proto/dos.h>
#include <devices/serial.h>
#include "defines.h"
#include "cus.h"
#include "serio.h"
#include "lbio.h"
#include "proto.h"


int setupmodem(char *cpSetup, char *cpLsys, char *cpHost)
{
	int rc;
	FILE *fpSetup = NULL;
	char *cpBuf = NULL;
	long wSetup;
	struct SerialHandle *serialhandle = NULL;
	LB *lb = NULL;
	int i, j;
	int bps;
	char *cp;
	char *cpCur;

	if ((fpSetup = fopen(cpSetup, "r")) == NULL)
		CU(FALSE);
	if (fseek(fpSetup, 0L, SEEK_END) == -1L)
		CU(FALSE);
	if ((wSetup = ftell(fpSetup)) == -1L)
		CU(FALSE);
	if (fseek(fpSetup, 0L, SEEK_SET) == -1L)
		CU(FALSE);
	if ((cpBuf = (char *)malloc(wSetup)) == NULL)
		CU(FALSE);
	if ((fread(cpBuf, wSetup, 1, fpSetup) != 1) && ferror(fpSetup))
		CU(FALSE);
	if ((wSetup = cnvbuf(cpBuf, cpBuf+wSetup-1)) == 0)
		CU(FALSE);
	if ((lb = lbopen(cpBuf, cpBuf+wSetup-1)) == NULL)
		CU(FALSE);
	if (lbseek(lb, 0, LBSEEK_SET) == NULL)
		CU(FALSE);
	if (wSetup == 0)
        CU(FALSE);
	if ((serialhandle = CreateSerialHandle(0L, 0L)) == NULL)
		CU(FALSE);
	if ((bps = lsysbps(cpLsys, cpHost)) == 0)
		CU(FALSE);
	if (!SetSerialParameters(serialhandle, bps, 0L))
		CU(FALSE);

	do {
		if ((lb->lb_wLnCur != 0) && (*(lb->lb_cpLnCur) != '#')) {
			for (i=0, cp = lb->lb_cpLnCur; i < lb->lb_wLnCur; i++, cp++)
				if (*cp == ':')
					break;
			if ((*cp == ':') && (i == strlen(cpHost)))
				if (!(strnicmp(lb->lb_cpLnCur, cpHost, i))) {

					if (*(cp+1) == NL)
						CU(TRUE);

					for (j = 0; j < 3; j++) {
						if (WriteSerial(serialhandle, "+", 1) != 1)
							CU(FALSE);
						Delay(10); /* 10*1/50 sec = 1/5 sec */
					}

					for ( ; ; ) {
						cpCur = ++cp;
						while (*cp != ',' && *cp != NL)
							++cp;
						WriteSerial(serialhandle, cpCur, cp - cpCur);
						WriteSerial(serialhandle, "\r", 1);
						Delay(5); /* 5*1/50 sec = 1/10 sec */
						if (*cp == NL)
							CU(TRUE);
					}
				}
		}
	} while (lbseek(lb, 1, LBSEEK_CUR));

	rc = FALSE;

CUS:
	if (lb)
		lbfree(lb);
	if (serialhandle)
		DeleteSerialHandle(serialhandle);
	if (fpSetup)
		fclose(fpSetup);
	if (cpBuf)
		free(cpBuf);
	return rc;
}

