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

int main(int argc, char **argv) {

	int j;
	
	if(argc < 2) {
		printf("pass the name of the file as a command line argument\n");
		return -1;
	}
	

	for(j=1; j<argc; j++) {
		FILE *fp;
		char *memfile, *ptr;
		int filesize, i;
		int lines = 0;
		
		if(!(fp = fopen(argv[j], "rb"))) {
			fprintf(stderr, "Could not open file %s for reading\n", argv[j]);
			continue;
		}
	
		fseek(fp, 0, SEEK_END);
		filesize = ftell(fp);
	
		ptr = memfile = malloc(filesize);
	
		fseek(fp, 0, SEEK_SET);
		for(i=0; i<filesize; i++) {
			fread(ptr++, 1, 1, fp);
		}
	
		fclose(fp);
	
		if(!(fp = fopen(argv[j], "wb"))) {
			fprintf(stderr, "Could not open file %s for writing\n", argv[j]);
			free(memfile);
			continue;
		}
	
		ptr = memfile;
		for(i=0; i<filesize; i++) {
			if(*ptr != 13) {
				fwrite(ptr, 1, 1, fp);
			} else {
				lines++;
			}
			ptr++;
		}

		printf("%s - %d lines fixed", argv[j], lines);
		
		if(memfile[filesize - 1] != '\n') {
			fputc('\n', fp);
			printf(", and fixed newline @ eof\n");
		} else {
			putchar('\n');
		}
	
		fclose(fp);
		free(memfile);
	}
	
	return 0;
}
