#include <iostream>
#include <fstream>
using namespace std;

char* itoa( int value, char* result, int base ) {
	
	// check that the base if valid
	
	if (base < 2 || base > 16) { *result = 0; return result; }
	char* out = result;
	int quotient = value;
	do {
    	*out = "0123456789abcdef"[ std::abs( quotient % base ) ];
    	++out;
    	quotient /= base;
	
	} while ( quotient );
	// Only apply negative sign for base 10
	if ( value < 0 && base == 10) *out++ = '-';
	std::reverse( result, out );
	*out = 0;
	return result;
}

int main (int argc, char* argv[]) {
  ofstream myfile;
  int processors = atoi(argv[1]);
  int rowst = atoi(argv[2]);
  int cols = atoi(argv[3]);
  int clusters = atoi(argv[4]);
  cout<<"procs = "<<processors<<endl;
  int rows;
  for(int i=0; i< processors; i++){
  	  rows = rowst/processors;
      char nameFilePrefix[] = "p";
  	  char nameFilePostfix[] = ".names";
  	  char dataFilePostfix[]= ".data";
      char nameFilev[50];
      char dataFile[50];
      char myrank[10];
	  itoa(i,myrank,10);
	  strcpy(nameFilev,nameFilePrefix);
	  //strcat(nameFilev,myrank);
	  strcat(nameFilev,nameFilePostfix); 
	  cout<<"name file = "<< nameFilev << endl;
	  myfile.open(nameFilev);
	  myfile << rows <<" "<<cols << endl;
  	  for(int i=0; i< rows; i++){
  		  myfile <<"R"<<i;
  		  if(i != (rows -1)) myfile<<" "; 
  	  }
  	  myfile<<"."<<endl;
  	  for(int j=0; j< cols; j++){
  		 myfile<<"C"<<j;
  		 if(j != (cols-1)) myfile <<" ";
  	  }
  	  myfile<<"."<<endl;
  	  myfile.close();
  
      strcpy(dataFile,nameFilePrefix);
	  strcat(dataFile,myrank);
	  strcat(dataFile,dataFilePostfix); 
	  
	   cout<<"creating matix"<<endl; 
	  int matrix[rows][cols];
  	  int x = rows/clusters;
  	  int y = cols/clusters;
  	  
  	  cout<<"data file "<<dataFile<<endl;
 	  myfile.open (dataFile);
 	  
 	  for(int i=0; i < cols; i++){
 	  	if(i != cols-1)
		  	myfile<<"Column"<<i<<"\t";
	  	else
	  		myfile<<"Column"<<i<<endl;
	  }
 	  
  	  //myfile << rows <<" "<<cols << endl;
  	  for(int i=0; i< rows; i++){
  	  	    
  	    	for(int j=0; j< cols; j++){
  	    		int datum;
  		 		if((i/x)==(j/y))
  		    		 datum = i/x+1;
  		 		else
  		    	 	datum = 0;
  		 		matrix[i][j] = datum;    
  	     		//myfile<<datum<<" ";
     		 }
   			  //myfile<<endl;
  		}
  		//myfile<<endl;
 	 	for(int i=0; i< rows; i++){
  			int xf,yf;
  			myfile<<"Row"<<i<<"\t";
  			if(i%2 == 0) xf = (i+x)%rows;
  			else xf = i;
  			for(int j=0; j<cols;  j++){
  	   		if(j%2 == 0) yf = (j+y)%cols;
  	   		else yf = j;
       		myfile<<matrix[xf][yf]<<"\t";
  	 	}
  	 	myfile<<endl;
 	 }
  	 myfile<<endl;
  
  
   	 myfile.close();
  }
  return 0;
}
