/* Fairlight's ICB Client                                                    */
/* Copyright 1994, Mark Luljak <fairlite@arcadia.aldridge.sol.net>           */
/*                                                                           */


#include "flicb.h"

/* Function:  connecticb()                      */
/* Arguments: none                              */
/* Purpose:  call clientsock() to open a port   */

int connecticb()
{
     int s;

     if ((s = clientsock(SERVERNAME, ICBPORT)) < 0) {
          printf("Unable to connect to server.\n");
          exit(1);
     }
     fcntl(s,F_SETFL,O_NDELAY);
     return(s);
}



/* Function:  login()                           */
/* Arguments: s        : socket descriptor      */
/*            logname  : login name to send     */
/*            nickname : nickname to send       */
/*            groupname: group name to send     */
/* Purpose:   Send a login packet to the server */

/* Packet format:  alogname^Anickname^Agroupname^A^A   */

void login(s, logname, nickname, groupname)
int s;
char *logname, *nickname, *groupname;
{
     char wholestring[STRINGSIZE];
     char pkt[STRINGSIZE];
     char a;
     
     sprintf(wholestring,"a%s%s%s%s%s%s%s",logname,SEPCHR,nickname,SEPCHR,
             groupname,SEPCHR,SEPCHR);     /* Concatenate packet    */
     a=(char)strlen(wholestring);          /* Get length of packet  */
     sprintf(pkt,"%c%s",a,wholestring);    /* Tack it onto string   */
     send(s,pkt,strlen(pkt),0);            /* Send it out on socket */
     return;
}




int packet_write(socket, packet)
int socket;
char *packet;
{
    char *ptr;
    int rval;
    unsigned char tosend;

    tosend = (char)strlen(packet)+1;
    ptr = packet;
    while ((rval = send(socket, &tosend, sizeof(unsigned char), 0)) < 0) {
	if (errno != EWOULDBLOCK) {
	    perror("packet_write");
	    return(-1);
	}
    }
    if (! rval) {
	return(-2);
    }
    while (tosend) {
        if ((rval = send(socket, ptr, tosend - (ptr - packet), 0)) < 0) {
	    if (errno != EWOULDBLOCK) {
	        perror("packet_write");
	        return(-1);
	    }
	} else {
	    if (! rval) {
		return(-2);
	    } else {
		tosend -= rval;
	        ptr += rval;
	    }
	}
    }
    return(0);
}

