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

#define	BUFFER_LEN	(80+1+1)

const char *extension  = ".rev";

typedef struct node {
	char		buffer[BUFFER_LEN];
	struct node	*next;
} t_node;

int
main(int argc, char **argv)
{
	FILE	*fp;
	char	 buffer[BUFFER_LEN];
	t_node	*list = NULL;
	char	*outfile;

	if (argc != 2) {
		fprintf(stderr, "Usage: %s filename\n", argv[0]);
		exit(1);
	}

	if ((fp = fopen(argv[1], "r")) == NULL) {
		fprintf(stderr, "Unable to open input file \"%s\": %s\n",
			argv[1], strerror(errno));
		exit(1);
	}

	while (fgets(buffer, sizeof(buffer), fp) != NULL) {
		t_node *cur = (t_node *) malloc(sizeof(t_node));
		strcpy(cur->buffer, buffer);
		cur->next = list;
		list = cur;
	}
	fclose(fp);	/* Close our input file stream */

	/* Don't forget '+ 1' for the the nul byte */
	outfile = (char *) malloc (strlen(argv[1]) + strlen(extension) + 1);
	if (outfile == NULL) {
		fputs("No memory to store output file name\n", stderr);
		exit(1);
	}

	strcpy(outfile, argv[1]);
	strcat(outfile, extension);

	if ((fp = fopen(outfile, "w")) == NULL) {
		fprintf(stderr, "Unable to open output file \"%s\": %s\n",
			outfile, strerror(errno));
		exit(1);
	}

	while (list) {
		int i;
		t_node *del = list;
		for (i = strlen(list->buffer) - 1; i >= 0; --i)
			fputc(list->buffer[i], fp);
		list = list->next;
		free(del);
	}

	fclose(fp);	/* Close our output file stream */

	free(outfile);	/* Free up the memory that we
			 * allocated for the output file name
			 */

	return 0;
}
