/* fileclient.c */

#include <stdlib.h>
#include <stdio.h>
#include <cnaiapi.h>
#include <sys/stat.h>
#include <unistd.h>

#define BUFFSIZE		256
#define INPUT_PROMPT		"Input   > "
#define RECEIVED_PROMPT		"Received> "

int recvln(connection, char *, int);
int readln(char *, int);

/*-----------------------------------------------------------------------
 *
 * Program: fileclient
 * Purpose: contact a fileserver and allow users to chat
 * Usage:   fileclient <compname> <appnum>
 *
 *-----------------------------------------------------------------------
 */
int
main(int argc, char *argv[])
{
	computer	comp;
	connection	conn;
	char		buff[BUFFSIZE];
	int		len;
	FILE		*lesen;
	int		laenge;
	struct stat	attrib;
	int		gesendet;

	if (argc != 4) {
		(void) fprintf(stderr, "usage: %s <compname> <appnum> <filename>\n",
			       argv[0]);
		exit(1);
	}

//	filename 

	if ((lesen = fopen (argv[3], "r")) == NULL)
	{
		perror ("Fehler beim Oeffnen!");
		exit(1);
	}

	if (lstat (argv[3], &attrib))
	{
		perror ("Fehler beim Auslesen!");
		exit(1);
	}

	laenge = (long) attrib.st_size;

	/* convert the compname to binary form comp */

	comp = cname_to_comp(argv[1]);
	if (comp == -1)
		exit(1);

	/* make a connection to the fileserver */

	conn = make_contact(comp, (appnum) atoi(argv[2]));
	if (conn < 0) 
		exit(1);

	(void) printf("File Connection Established.\n");
	send(conn, argv[3], strlen(argv[3]), 0);
	send(conn, "\n", 1, 0);
	send(conn, &laenge, sizeof(int), 0);

	gesendet = 0;

	/* iterate, reading from local file and send to fileserver */

	while(1) {
		if (gesendet >= laenge) break;
		fread(buff, sizeof(char), BUFFSIZE, lesen);
		(void) send(conn, buff, BUFFSIZE, 0);
		gesendet += BUFFSIZE;
		printf ("%d von %d gesendet.\n", gesendet, laenge);

	}

	/* iteration ends when stdin or the connection indicates EOF */

	fclose(lesen);

	(void) printf("\nFile Connection Closed.\n");
	(void) send_eof(conn);
	exit(0);
}

