// Word Wrap Version 1.0
// By Ben a.k.a DreamVB

//Syntex
//wraptext sample.txt /30

#include <iostream>
using namespace std;
using std::cout;
using std::endl;

int main(int argc, char *argv[]){
	FILE *fp = NULL;
	char c = '\0';
	string sFlag = "";
	int curpos = 0;
	int ln_len = 80;

	if (argc < 2){
		cout << "Usage: " << argv[0] <<
			" <Filename> [Wrap]" << endl;
		exit(1);
	}

	if (argc == 3){
		sFlag = argv[2];
		sFlag.erase(0, 1);
		//Get line length
		ln_len = atoi(sFlag.c_str());
	}

	//Open file.
	fp = fopen(argv[1], "r");
	
	if (fp == NULL){
		cout << "IO/Error, Cannot open file:" <<
			endl << argv[1] << endl;
		exit(1);
	}
	
	//Read in the file one char at a time.
	while ((c = fgetc(fp))!=NULL){
		if (feof(fp)){
			break;
		}

		//Check curpos
		if (curpos >= ln_len){
			//Append new line
			fputc('\n', stdout);
			//Rset char pos
			curpos = 0;
		}
		
		fputc(c, stdout);
		//INC line length counter
		curpos++;
	}

	//Close file
	fclose(fp);

	return 0;
}