/*
 * conv_file.c
 * This program reads an input file and converts it to upper or lower case.
 */

#include <stdio.h>

int main (int argc, char **argv)
{
  FILE   *p_infile;            /* The input file. */
  int    c;                    /* The current character read. */
  FILE   *p_outfile;           /* The output file. */
  int    to_upper;             /* Convert to upper or to lower case. */
  int    n_chars = 0;          /* Number of characters read. */
  int    n_conv = 0;           /* Number of characters converted. */

  /* Check the number of arguments to the program: */
  if (argc < 4)
  {
    printf ("Usage: %s <input file> <output file> -[l/u]\n", argv[0]);
    return (1);
  }

  /* Determine the work mode, determined by argv[3] */
  if (strcmp(argv[3], "-u") == 0 || strcmp(argv[3], "-U") == 0)
  {
    to_upper = 1;
  }  
  else if (strcmp(argv[3], "-l") == 0 || strcmp(argv[3], "-L") == 0)
  {
    to_upper = 0;
  }
  else
  {
    printf ("Unknown option: %s\n", argv[3]);
    return (1);
  }

  /* Open the input file, specified by argv[1] */
  p_infile = fopen (argv[1], "r");

  if (p_infile == NULL)
  {
    printf ("Failed to open the input file '%s'.\n", argv[1]);
    return (1);
  }

  /* Prepare the output file, specified by argv[2] */
  p_outfile = fopen (argv[2], "w");

  if (p_outfile == NULL)
  {
    printf ("Failed to open the output file '%s'.\n", argv[2]);
    fclose (p_infile);
    return (1);
  }

  /* Read the file, character by character. */
  while ((c = fgetc(p_infile)) != EOF)
  {
    n_chars++;

    /* Convert the character as needed. */
    if (to_upper && (c >= 'a' && c <= 'z'))
    {
      c += ('A' - 'a');
      n_conv++;
    }
    else if (!to_upper && (c >= 'A' && c <= 'Z'))
    {
      c += ('a' - 'A');
      n_conv++;
    }

    /* Write the character to the output file. */
    fputc (c, p_outfile);
  }

  /* Print statistics to the output file. */
  fprintf (p_outfile, "\n**************** Summary: ****************\n");
  fprintf (p_outfile, "Read %d characters.\n", n_chars);
  fprintf (p_outfile, "Converted %d characters.\n", n_conv);
  fprintf (p_outfile, "******************************************\n");

  /* Close the files. */
  fclose (p_infile);
  fclose (p_outfile);

  return (0);
}

