#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#define ACKNOLEDGE_EXECUTION_OK     "OK"
#define ACKNOLEDGE_EXECUTION_ERR    "ERROR"

#define  PORT  10000                  //PORT ADDRESS
#define  HOST  "zeus"                 //HOST
#define  ACKNOWLEDGE_SIZE   100       
#define  MESSAGE_SIZE       28800
int readfits(char *buffer)
{
    FILE *fp;
    int c;

    fp = fopen("header.fits", "r");

    if (fp == NULL)
    {
        printf("impossible d'ouvrir le fichier\n");
        return 1;
    }

    while ((c = getc(fp)) != EOF)
    {
        *buffer = c;
        buffer++;

    }

    return 0;

}

    

int main()
{
    char    ack[ACKNOWLEDGE_SIZE];    //FITS HEADER
    int     sd;                       //SOCKET DESCRIPTOR
    struct  sockaddr_in pin;          //BORDEL POUR SOCKET
    struct  hostent     *hp;
    char    message[MESSAGE_SIZE];
    int     received;

    //Find the server
    if ((hp = gethostbyname(HOST)) == 0)
    {
        perror("SLAVE: SERVER UNKNOWN");
        free(message);
        exit(1);
    }

    //FILL the socket structure with host information
    bzero(&pin, sizeof(pin));
    pin.sin_family = AF_INET;
    pin.sin_addr = *(struct in_addr *)(hp->h_addr);
    pin.sin_port = htons(PORT);

    //Get an internet socket 
    if ((sd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        perror("SLAVE: socket UCCI");
        close(sd);
        free(message);
        exit(1);
    }

    //Connect to PORT on HOST
    if (connect(sd, (struct sockaddr *) &pin,sizeof(pin)) == -1)
    {
        perror("SLAVE: connect");
        close(sd);
        free(message);
        exit(1);
    }

    //printf("Connection established\n");

    //Send a message
    readfits(&message[0]);
    if (send(sd, message, strlen(message), 0) == -1)
    {
        perror("SLAVE: send");
        close(sd);
        free(message);
        exit(1);
    }

    strcpy(ack,"");
    //Get the message from the client
    if((received = recv(sd, ack, ACKNOWLEDGE_SIZE, 0)) == -1)
    {
        perror("SLAVE: received");
        close(sd);
        exit(1);
    }
    ack[received] = NULL;
    //printf("RECEPTION Acknowledge : %s \n", ack);

    strcpy(ack,"");
    //Get the message from the client
    if((received = recv(sd, ack, ACKNOWLEDGE_SIZE, 0)) == -1)
    {
        perror("SLAVE: received");
        close(sd);
        exit(1);
    }
    ack[received] = NULL;

    if (strcmp(ack,ACKNOLEDGE_EXECUTION_ERR) == 0)
    {
        printf("RESULT Acknowledge : %s \n", ack);
    }

    close(sd);

    return 0;
}

