// ffile4.cpp -- Gets the name of a file from the user, 
//               say it is "moo.dat".
//               It copies it to file "moo.datout", changing all letters 
//               to capitals and replacing streaks of whitespaces by 
//               a single space.

#include <iostream>  // It allows us to use cin, cout
#include <fstream>   // It allows us to use ifstream, ofstream ..
#include <string>    // It allows us to use strings

using namespace std;

int main (void){
    string inFName;  // Name of the input file
    string outFName; // Name of the output file

    // Read the name of the input file from standard input
    cout << "Enter a File Name: ";
    cin >> inFName;

    // Compute the name of the output file
    outFName = inFName + "out";

    // Open input and output files
    ifstream fin;
    fin.open(inFName.c_str());
    if (fin.fail()){
	   cout << "Cannot open " << inFName << endl;
	   exit(1);
    }
    ofstream fout (outFName.c_str());
    if ( ! fout ) {
	cout << "Cannot open " << outFName << endl;
	exit(1);
    }

    char current;        // The character just read
    char previous = 'a'; // The character read the last time. It is
	                     // initialized to a non-space character to
	                     // make clear that at the start the previous
	                     // character is not a space.
    while ( fin.get(current) ){
       if ((!isspace(current)) || (!isspace(previous)) || (current == '\n')){
          // isspace returns a non zero value iff its argument is a space
          // character, that is something like ' ', '\t', '\n'.
		  // We have the (current == '\n') clause to make sure that we
		  // do not skip lines.
          current = toupper(current); 
          // toupper converts a letter to uppercase
          // and leaves all other characters unchanged.
          fout.put(current);
          cout.put(current);
       }
       previous = current;
    }
    fin.close();
    fout.close();

    return 0;
}

