/* 
   Copyright (C) 1999 E. H. Haley

   crop.c-- crops out the largest possible 2^m x 2^n piece of a jpeg.
   cropsq.c-- the largest 2^n x 2^n piece

   cropsqs.c-- crops out as many nonoverlapping 2^n x 2^n squares as
   possible and saves them to outprefix.i.outsuffix, i=0,1,...

   It centers them in the, um, smaller dimension.  In the larger dim,
   aligns them top or left, (so to speak, given that on account of GL,
   mine are upside-down) */

#include <stdio.h>
#include <jpeglib.h>
#include <jerror.h>
#include "lib/loadj.h"

int main(int aardc, char **aardv)
{
  char *infile, *outpre, *outsuf, outfile[256];
  JSAMPLE *arr, *newarr;
  int i,j,k,l,p, w,h,c, logw=-1,logh=-1, neww=1,newh=1, side, npix, offw,offh;

  if (aardc<4) exit(0);
  else { infile=*++aardv; outpre=*++aardv; outsuf=*++aardv; }

  arr = rjf(infile, &w, &h, &c);

  while((neww<<=1)<=w) logw++;
  neww>>=1;
  while((newh<<=1)<=h) logh++;
  newh>>=1;

  if (neww<newh)
    {
      side=neww;
      offw=(w-side)/2;
      offh=h%side;
      npix=newh/neww;
      newarr=(JSAMPLE *)calloc(c*side*side, sizeof(JSAMPLE));
      for(p=0; p<npix; p++)
	{
	  for(i=0; i<side; i++)
	    for(j=0; j<side; j++)
	      for(k=0; k<c; k++)
		newarr[(i+side*j)*c+k]=arr[((i+offw)+w*((j+offh)+p*side))*c+k];
	  sprintf(outfile,"%s.%d.%s",outpre,p,outsuf);
	  wjf(newarr, outfile, &side, &side, &c);
	}      
    }
  else
    {
      side=newh;
      offh=(h-side)/2;
      npix=neww/newh;
      newarr=(JSAMPLE *)calloc(c*side*side, sizeof(JSAMPLE));
      for(p=0; p<npix; p++)
	{
	  for(i=0; i<side; i++)
	    for(j=0; j<side; j++)
	      for(k=0; k<c; k++)
		newarr[(i+side*j)*c+k]=arr[((i+p*side)+w*(j+offh))*c+k];
	  sprintf(outfile,"%s.%d.%s",outpre,p,outsuf);
	  wjf(newarr, outfile, &side, &side, &c);
	}      
    }

  free(newarr);
  exit(npix);
}




