//==============================================================================
//
// pgmselect.c
//
// use:
// pgmselect file.pgm x0 y0  nWid  nHei  result.pgm
//
//==============================================================================

#include <stdio.h>
#include <memory.h>
#include "pgm.h"

//==============================================================================
int GetBlock(byte* pImg, int nWidth, int nHeight, int xCoord, int yCoord,
              byte* pBlock, int blkWidth, int blkHeight)
{
  int i;
  int nShift;

  if(nHeight<(yCoord+blkHeight) || nWidth<(xCoord+blkWidth)) 
  {
    printf("GetBlock: err! %d %d %d %d ", nWidth, nHeight, xCoord, yCoord);
    return 1;
  }
  for(i=0; i<blkHeight; i++)
  {
    nShift = (yCoord + i) * nWidth + xCoord;
    memcpy(pBlock + i*blkWidth, pImg+nShift, blkWidth);
  }
  return 0;
}

//==============================================================================
int main(int nArg, char** ppArg)
{
	int i, ii;
	int nW, nH; // image width and height
	int nB;     // image brightness
	byte* pIm;  // pointer to image matrix
	int nSize;  // image size in bytes
	int x0, y0, nW2, nH2;
	byte* pIm2;  // pointer to second image matrix 
	
	if(nArg==1) 
	{
		puts("select subimage in rectangle");
		puts("pgmselect file.pgm x0 y0  nWid  nHei  result.pgm");
		exit(1);
	}
	ReadPGM(ppArg[1], &pIm,  &nW, &nH);
	x0  = atoi(ppArg[2]);
	y0  = atoi(ppArg[3]);
	nW2 = atoi(ppArg[4]);
	nH2 = atoi(ppArg[5]);
	
	nSize = nW2 * nH2;
	pIm2 = (byte*) malloc(nSize); 
	
	GetBlock(pIm, nW, nH, x0, y0, pIm2, nW2, nH2);

	WritePGM(ppArg[6], pIm2, nW2, nH2);
	
	free(pIm2);
	free(pIm);
	
	return 0;
}