/*
 * Copyright 1995 TriloBYTE Software Solutions.
 *
 * read an image from stdin and send it to the server
 * -s server name
 * -p port number
 *
 * Author: Amen Zwa, TriloBYTE.
 */



static char* sccsid = "%W%\t%G%\tAmen Zwa, TriloBYTE.";



/* isend.c: image client */



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "imgclt.h"



#define NUMFRAME	240
#define STRLEN		80

static char buf[STRLEN];



static void error(const char* s)
{
    fprintf(stderr, "imgclt: %s\n", s);
}



/* function called after disconnect */
void disconn_func(void* usrdata)
{
    printf("\
Disconnected from server %s.\n\
Data rate = %.2f KB/sec\n\
Frame rate = %.2f fps\n",
    (char*)usrdata, IGetDataRate(), IGetFrameRate());
}



int main(int argc, char** argv)
{
    char svrname[STRLEN];
    unsigned char *r = 0, *g = 0, *b = 0, *c = 0;
    float col, coldel;
    int i, x, y, wdt, hgt, ndx, size, svrport = I_SvrPort;
    int cin, do_rgb = 0;
    extern char *optarg;

    wdt = I_Width;
    hgt = I_Height;

    gethostname(svrname, STRLEN);
    while ((i = getopt(argc, argv, "s:p:rhx:y:")) != EOF)
	switch (i) {
	case 's':
	    strcpy(svrname, optarg);
	    break;
	case 'p':
	    svrport = atoi(optarg);
	    break;
	case 'r':
	    do_rgb = 1;
	    break;
	case 'x':
	    wdt = atoi(optarg);
	    break;
	case 'y':
	    hgt = atoi(optarg);
	    break;
	case 'h':
	case '?':
	    error("Usage: isend [-s svrname] [-p svrport] [-r] [-x width] [-y height]");
	    break;
	}

    IConnect(svrname, svrport);
    ISetDisconnFunc(disconn_func, (void*)svrname);

    if (wdt != I_Width || hgt != I_Height) IDimension(wdt, hgt);
    size = wdt * hgt;

    if (do_rgb) {
       r = (unsigned char*) calloc(size, sizeof(unsigned char));
       g = (unsigned char*) calloc(size, sizeof(unsigned char));
       b = (unsigned char*) calloc(size, sizeof(unsigned char));
       for (;;) {
	  for(i=0; i<size; i++) {
	     if ((cin=getc(stdin)) == EOF) goto ex; else r[i] = cin;
	     if ((cin=getc(stdin)) == EOF) goto ex; else g[i] = cin;
	     if ((cin=getc(stdin)) == EOF) goto ex; else b[i] = cin;
	     }

	  IColorRGB(r, g, b, size);
	  }
       }

    else {
       c = (unsigned char*) calloc(size, sizeof(unsigned char));
       for (;;) {
	  for(i=0; i<size; i++)
	     if ((cin=getc(stdin)) == EOF) goto ex; else c[i] = cin;

	  IColorIndex(c, size);
	  }
       }

ex: printf("end of data\n");

    sleep(2);  
    free(r);
    free(g);
    free(b);
    free(c);
    IDisconnect();
    return 0;
}
