#include <iostream.h>
#include <stdio.h>
#include <string.h>

#define ERR_MSG "\nError: "
#define WARN_MSG "\nWarning: "
#define BUF_SIZE 2048
#define HEADER_LEN_INT 4
#define HEADER_SHORT 2


void writeHeader(FILE *out, int xLen, int yLen)
{
	fprintf(out, "P2\n");
	fprintf(out, "# CREATOR: SelectPic 1996\n");
	fprintf(out, "%i %i\n", xLen, yLen);
	fprintf(out, "255\n");
}

int writePic(char *outfile, FILE *picture, int x1, int y1, 
	      int xLen, int yLen, int Sx, int Sy)
{

	char buf[BUF_SIZE];
	int i, j, pix, dummy;
	FILE *out;

        if ((out = fopen(outfile, "wt")) == NULL)
        {
           cout << ERR_MSG << "Cannot open " << outfile << " !!!\n";
           return -1;
        }
	writeHeader(out, xLen, yLen);

	// start at the beginning of the picture
	rewind(picture);
        // ignore header
        for(i=0;i<HEADER_LEN_INT;i++)
                fgets(buf,BUF_SIZE, picture);
 
	// find start pixel
	for(i=0;i<(y1*Sx + x1);i++) fscanf(picture, "%i", &dummy) ;

	// copy the sub picture
	for(i=0;i<yLen;i++) // for each line in the sub-picture
	{
		for(j=0;j<xLen;j++)
		{
			fscanf(picture, "%i", &pix);
			fprintf(out, "%i ", pix); 
		}
		fprintf(out, "\n"); 
		// skip the rest of the line
		for(j=0;j<(Sx-xLen);j++) fscanf(picture, "%i", &dummy);
	}	
	fclose(out);
	return 0;
}

 
int main()
{
	char subStart[30], picFile[30], subname[100];
	char buf[BUF_SIZE];
	int xLen, yLen, no_pics, bigX, bigY, x1, y1, i;
	long seed;
	FILE *bigPic;

	cout << "\nPicture file (ASCII-TEXT)  : ";
	cin >> picFile;

	cout << "\nStart of Sub-Picture-files : ";
	cin >> subStart;

	cout << "\nRandom Number (seed)       : ";
	cin >> seed;

	cout << "\nNumber of Sub-Picture      : ";
	cin >> no_pics;

	cout << "\nX-Size of Sub-Picture      : ";
	cin >> xLen;

	cout << "\nY-Size of Sub-Picture      : ";
	cin >> yLen;


	if ((bigPic = fopen(picFile, "rt")) == NULL)
        {
           cout << ERR_MSG << "Cannot open " << picFile << " !!!\n";
           return -1;
        }

	// ignore header
        for(i=0;i<HEADER_SHORT;i++)
                fgets(buf,BUF_SIZE, bigPic);
	fscanf(bigPic, "%i%i", &bigX, &bigY);
	cout << "\nPicture File: " << picFile ;
	cout << "  Size  x: " << bigX << "   y: " << bigY;

	srand( seed );
	for(i=0;i<no_pics;i++)
	{
		sprintf(subname, "%s.%i", subStart, i);
		x1 = rand() % (bigX-xLen);
		y1 = rand() % (bigY-yLen);
		cout << "\n Write to file: " << subname;
		cout << "  x1: " << x1;
		cout << "  y1: " << y1;
		writePic(subname, bigPic, x1, y1, xLen, yLen, bigX, bigY);
	}

	fclose(bigPic);
	return 0;
}




