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

#define MAXLINE 128
char *newLine(FILE *infile) {
  int i, ch;
  char *s = NULL;
  char line[MAXLINE];
  int lineLen = 0;
  if (feof(infile)) return NULL;
  /* Read the line into a local buffer upto newline */
  ch = fgetc(infile);
  while ((ch != EOF) && (ch != '\n')) {
    if (lineLen < sizeof(line)-1) line[lineLen++] = ch;
    ch = fgetc(infile);
  }
  /* Allocate a string to hold it, copy and return */
  s = malloc(lineLen+1);
  for (i = 0; i<lineLen; i++) s[i] = line[i];
  s[i] = '\0';
  return s;
}
  
struct lineNode {
  char *line;
  struct lineNode *next;
};

struct lineNode *lines = NULL;

struct lineNode *reverse(struct lineNode *p) {
  struct lineNode *res = NULL;
  struct lineNode *nxt;
  while (p) {
    nxt = p->next;
    /* you fill in the rest of this loop body */
  }
  return res;
}

int main(int argc, char *argv[]) {
  FILE *infile = stdin;
  FILE *ofile = stdout;
  struct lineNode *lnode;
  char *s;

  if (argc >= 3) ofile = fopen(argv[2],"w");
  if (argc >= 2) infile = fopen(argv[1],"r");

  s = newLine(infile);
  while (s) {
    lnode = (struct lineNode *) malloc(sizeof(struct lineNode));
    lnode->line = s;		/* Fill in value */
    lnode->next = lines;
    lines = lnode;
    s = newLine(infile);
  }
  //  lines = reverse(lines);
  for (lnode = lines; lnode != NULL; lnode = lnode->next) {
    fprintf(ofile,"%s\n", lnode->line);
  }
  fclose(ofile);
  return 0;
}
