#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stat.h>

#define UNKNOWN_FILE    "Unknown file or disk protected ! \n"
#define OVERWRITE       "Can't copy this file over itself \n"
#define ERROR           "Error !!!\n"
#define SAVE_ERROR      "Can't Save file \n"
#define LF              '\n'
#define SPACE           ' '
void lf_killer(char word[],char sortie[],long int len);

main(int argc,char *argv[])
{
    char *Version = "$VER: LF Killer V1.0 by TRINH Eric";
    FILE *fp1;
    char *word;
    struct stat etat;
    long int len;
    if (argc < 3 )
    {
	printf("Usage: LF_Killer <input> <output> \n");
	printf("Written by Eric TRINH\n");
	exit(EXIT_FAILURE);
    }
    if (!strcmp(argv[1],argv[2]))
    {    
	printf( OVERWRITE );
	exit(EXIT_FAILURE);
    }
    fp1 = fopen(argv[1],"r");
    if (fp1 ==NULL)
    {
       printf(UNKNOWN_FILE);
       exit(EXIT_FAILURE);
    }
    stat(argv[1],&etat);
    len = etat.st_size;
    word = (char *)malloc((size_t )len * sizeof(char));
    fread(word,sizeof(char),len,fp1);
    fclose(fp1);
    lf_killer(word,argv[2],len);
    free(word);
}

void lf_killer(char word[],char sortie[],long int len)
{
    FILE *fp2;
    unsigned char car[2];
    long int ok,curs;

    fp2 = fopen(sortie,"w");
    if (fp2 == NULL)
    {
	printf(SAVE_ERROR);
	exit(EXIT_FAILURE);
    };
    for (curs=0 ; curs<len ; curs++)
    {
	if (word[curs] == LF)
	{
	    if (word[curs+1] == LF)
		++curs;
	    else if (word[curs+1] != SPACE)
		word[curs] = SPACE;
	    }
	ok=fputc(word[curs],fp2);
	if (ok == EOF)
	{
	    printf(ERROR);
	    fclose(fp2);
	    remove(sortie);
	    exit(EXIT_FAILURE);
	};
    };
    fclose(fp2);
}
