// program to use file stream functions
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int parse_args(int argc, char * argv[]);
void check_for_null(void *p, char *msg);

char * filename = NULL;
char * newFilename = NULL;
int seek_pos = -1;

int main(int argc, char *argv[]) {
  parse_args(argc, argv);

  FILE * fOut = NULL;
  
  // open file
  FILE * fIn = fopen(filename, "r");
  check_for_null(fIn, "Unable to open fIn file.");

  // if seek_pos set, seek to that position
  if (seek_pos > 0) {
    int retVal = fseek(fIn, seek_pos, SEEK_SET);
    if (retVal != 0) fprintf(stderr, "Error with fseek.\n");
  }

  // print out 10 bytes starting from seek_pos
  char s[10];  int num_read = -1;
  num_read = fread(s, sizeof(char), 10, fIn);
  if (num_read > 0) printf("%*s\n", num_read, s);
  else fprintf(stderr, "return value from fread: %d\n", num_read);


  // if copy specified, open new file, copy fIn
  if (newFilename != NULL) {
    fOut = fopen(newFilename, "w");
    check_for_null(fOut, "Unable to open fOut file.");

    // seek to begin of fIn
    int retVal = fseek(fIn, 0, SEEK_SET);
    if (retVal != 0) fprintf(stderr, "Error with fseek.\n");

    // read fIn, 10 bytes at a time
    while ((num_read = fread(s, sizeof(char), 10, fIn)) > 0) {
      fwrite(s, sizeof(char), num_read, fOut);
    }
    fclose(fOut);
  }
  
  
  // close files
  fclose(fIn);

  // note - with open file can also use fscanf, fprintf, etc.
  /*char s[100];
  fscanf(fIn, "%99s", s);
  printf("%s\n", s);*/
  
  
  return 0;
}


int parse_args(int argc, char * argv[]) {
  if (argc < 2) {
    printf("Usage: ./files filename.txt [-copy newfilename.txt] [-seek int_position] [-stats which]\n");
    printf("  If -copy specified, copy entire file.\n"
	   "  If -seek specified, seek to that location before printing 10 bytes.\n");
    exit(0);
  }

  filename = argv[1];

  for(int i=2; i < argc; i++) {
    
    if (strcmp(argv[i], "-copy") == 0 && argc > i)
      newFilename = argv[i+1];
    
    if (strcmp(argv[i], "-seek") == 0 && argc > i)
      seek_pos = atoi(argv[i+1]);
  }
}


void check_for_null(void *p, char *msg) {
  if (p == NULL) {
    fprintf(stderr, "NULL result, bad, %s\n", msg);
    exit(0);
  }
}