/*
Written by: James Scott 104305777
Course: Info 261
Group B
Professor Chris Davidson
Assignment Project 4, Disk Recursion
Description: This program calcuates the size of a directory given to it via a command line argument
and outputs the total in bytes and KB
*/
#include <iostream>
#include <iomanip>
#include <cmath>
#include <io.h>

using namespace std;

void listDirectories(double& totalSizeBytes,string directoryPath,string filespec);

int main (int argC,char* argV[]){
	
	// this tells you if you just ran the application rather then putting in a command line
	// argument with it.
	if (argC < 2)
	{
		cout << "This program only accepts command line arguments." << endl;
		exit (0);
	}
	
	string dirPath = argV[1]; // for storing the command line argument.

	double totalSizeBytes = 0; // for storing the size of all the files

	listDirectories (totalSizeBytes, dirPath, "*.*"); // this calculates the size of the directories.

	// this checks to see if there were any files found and if there are it outputs the info.
	if (totalSizeBytes == 0)
		cout <<"No files found!" << endl;
	else
		cout << "Total Space occupied in this directory in bytes is: " << fixed <<setprecision(0)<<totalSizeBytes << " bytes"
		<< endl << "Total Space occupied in this directory in KB is: " << totalSizeBytes/1024 << "KB" << endl;

	return 0;
}


// this is the directory listing function. 
void listDirectories (double& totalSizeBytes, string directoryPath, string filespec) {

	struct _finddata_t fileInfo;

	string fullPath = directoryPath; // This stores the path
	fullPath += "\\*.*"; // this adds \*.* to the path

	double hFindFile = _findfirst(fullPath.c_str(), &fileInfo);
	
	if (hFindFile == -1L)
	{
		cout << "No file found in this directory." << endl;
		exit (1);
	}
	else 
	{
		fullPath = directoryPath;
		fullPath += "\\";
		fullPath += fileInfo.name;
		do 
			if (fileInfo.attrib & _A_SUBDIR )
				if (strcmp(fileInfo.name,".") != 0  && strcmp(fileInfo.name,"..") != 0)
				{// if its neither . or .. it will open the directory and add up the sizes of 
				 // everything in that directory and anyting in that directory and so on by calling it self

					fullPath = directoryPath;
					fullPath += "\\";
					fullPath += fileInfo.name;

					listDirectories (totalSizeBytes, fullPath, filespec);

					totalSizeBytes += fileInfo.size;				
				}
		while (_findnext (hFindFile, &fileInfo) == 0);		
	_findclose (hFindFile);
	}

	fullPath = directoryPath;
	fullPath += "\\";
	fullPath += filespec;
	hFindFile = _findfirst(fullPath.c_str(), &fileInfo);

	if( hFindFile == -1L)
	{
		cout << "No file found in this directory." << endl;
		exit (1);
	}
	else
	{
		do
			if ( !(fileInfo.attrib & _A_SUBDIR))
				totalSizeBytes += fileInfo.size;
		while (_findnext (hFindFile, &fileInfo ) == 0);

		_findclose(hFindFile);
	}
}