//Deian Stefan
//Problem 3 -- im_send
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <errno.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "util.h"


int main(int argc, char *argv[]) {
	char buf[512]= {'\0'};
	char *pname, *hname, *sport;
	int sfd,from_cmd=0;
	unsigned short port;
	unsigned long readno;
	struct sockaddr_in sock_out;


	pname=*argv++;
	if(argc<3) {
		fprintf(stderr, "Usage: %s hostname port.\n",pname);
		return -1;
	}
	hname=*argv++;
	sport=*argv++;
	argc-=3;

	while(argc){
		strlcat(buf,*argv++,sizeof(buf));
		if(argc-1) {strlcat(buf," ",sizeof(buf)); }
		argc--;
		from_cmd=1;
	}
	readno=strlen(buf);

	if((sfd=socket(AF_INET,SOCK_DGRAM,0))<0) {
		fprintf(stderr,"Could not create socket: %s\n",
				strerror(errno));
		return -1;
	}

	sock_out.sin_family=AF_INET;
	if(get_addr(hname,&sock_out)) {
		close(sfd);
		return -1;
	}
	port=(unsigned short)strtol(sport,0,10);
	sock_out.sin_port=htons(port);

	if(!from_cmd && (readno=read(0,buf,sizeof(buf)))<0) {
		fprintf(stderr, "Failed to read from standard input.\n");
		close(sfd);
		return -1;
	}

	if(sendto(sfd,buf,readno,0,(struct sockaddr*)&sock_out,
			sizeof(sock_out))<0) {
		fprintf(stderr,"Failed to send message: %s\n",
				strerror(errno));
		close(sfd);
		return -1;
	}
	close(sfd);

	return 0;
}

