/*--------------------------------------------------*
 | Head.c - Unix-like utility.                      |
 | Syntax: head [-N] [file [file [ ... ] ]          |
 | Prints on stdout the first N (default: N_DEFVAL) |
 | lines read from the given files, or from stdin.  |
 | v1.00 MLO 911223                                 |
 *--------------------------------------------------*/

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "mlo.h"

#define N_DEFVAL      10
#define LINE_LENGTH   256

void DoTheStuff(FILE *fp, int n);
void Syntax(void);

void main(
  int argc,
  char **argv
){
  int nLines = N_DEFVAL;

  while (--argc) {
    if ( ((*++argv)[0] == '-') ) {
      if (isdigit((*argv)[1])) {
        if ((nLines = atoi(*argv+1)) < 1) Syntax();
      } else {
        Syntax();
      }
    } else if ((*argv)[0] == '?') {
      Syntax();
    } else {
      break;
    }
  }

  if (argc) {
    while (argc--) {
      FILE *fp;

      if ((fp = fopen(*argv, "r")) == NULL) {
        printf("head: couldn't open file \"%s\".\n", *argv);
      } else {
        DoTheStuff(fp, nLines);
        fclose(fp);
      }
      ++argv;
    }
  } else {
    DoTheStuff(stdin, nLines);
  }

  exit(SYS_NORMAL_CODE);
}

void DoTheStuff(
  FILE *fp,
  int n
){
  char line[LINE_LENGTH];

  while (n--) {
    if (fgets(line, LINE_LENGTH, fp)) {
      fputs(line, stdout);
    } else {
      puts("END-OF-FILE");
      break;
    }
  }
}

void Syntax(void)
{
  puts("\nUsage:   head [-N] [file [file [ ... ]]]");
  printf("Purpose: prints on stdout the first N (default: %d) lines read\n",
         N_DEFVAL);
  puts("         from the given file(s), or from stdin.\n");

  exit(SYS_NORMAL_CODE);
}
