/*  Convert cr-lf (DOS/Windows) to lf (Unix)
 *  line terminators.
 *  Written by Anthony W. Hursh.
 *  Released to the public domain.
 */

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


main(int argc, char *argv[])
{
    FILE *infile, *outfile;
    char tempName[1024];
    int c;
    if(argc != 2)
    {
	    fprintf(stderr,"Usage: dos2unix <textfile>\n");
            exit(1);
    }
    strcpy(tempName,argv[1]);
    strcat(tempName,"$$$");  // Create a new file name by appending $$$ to the old
                            //  file name. Hopefully this doesn't conflict with
                           //   anything.

    if((infile = fopen(tempName,"rb")) != NULL) // It already exists, so don't clobber it.
    {
	fprintf(stderr,"Temporary file %s already exists. Please delete it.\n",tempName);
	fclose(infile);
        exit(1);
    }
                            
    if((infile = fopen(argv[1],"rb")) == NULL)
    {
           fprintf(stderr,"%s: Can't open.\n",argv[1]);
           exit(1);
    }
    if((outfile = fopen(tempName,"wb")) == NULL)
    {
           fprintf(stderr,"%s: Can't open.\n",tempName);
           exit(1);
    }
    while((c = getc(infile)) != EOF)
    {
          if(c == '\r') // Carriage return, don't do anything.
               continue;
          else putc(c,outfile); // Otherwise write the character to the new file.
     }
    fclose(infile);
    fclose(outfile);
    unlink(argv[1]); // Delete old file.
    rename(tempName,argv[1]); // Rename new file to old name.
}

