#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <mvcd.h>
#include <matrixSHEN.h>  /*by SHEN*/
#include <cres.h>
#include <getopt.h>


int start, end;
int image_size ;

void Crop3DImage(int argc, char *argv[])
{
  unsigned char ***src, ***outp ;
  int  i,j,k,ii,jj,kk, /*image_size,*/ z_size, z_size_Output  ;
  FILE *fp;


  /* image size in xy plane */
  /*image_size=256;*/

  fp=myopen(argv[1],"rb");
  fseek(fp,0,SEEK_END);
  z_size=ftell(fp)/(image_size*image_size);
  rewind(fp);

  /* apply for memory */
  src  = UCalloc3d(image_size,image_size,z_size);
  z_size_Output = end-start+1 ; printf("z_size_Output=%d\n", z_size_Output) ;
  outp = UCalloc3d(image_size,image_size,z_size_Output);

  /* read data */
  for(k=0;k<z_size;k++)
    for(i=0;i<image_size;i++)
      fread(src[k][i],1,image_size,fp);
  fclose(fp);

  /* crop ... */
  if( end>0 )
    {
      for( k=start; k<=end && k<z_size; k++ )
	for( i=0; i<image_size; i++ )
	  for( j=0; j<image_size; j++ )
	    if( k>=0 )
	      outp[k-start][i][j] = src[k][i][j] ;
    }
  else
    printf("Notice: end slice is 0!\n") ;


  /* write the smoothed image */
  printf("Write file!\n") ;
  fp=myopen(argv[2],"wb");
  for(k=0;k<(end-start+1);k++)
    for(i=0;i<image_size;i++)
      fwrite(outp[k][i],1,image_size,fp);
  fclose(fp);

  /* free */
  UCfree3d(outp, z_size_Output, image_size) ;
  UCfree3d(src,  z_size,        image_size) ;
}




void show_usage()
{
    char fullVersion[] = "$Rev: 83 $"; //This line will be automatically 
                                       //populated by svn and should be
                                       //of the form "$Rev: 83 $" else it could
                                       //cause a segmentation fault
    char *shortVersion = strchr(fullVersion,' ')+1; //Eliminate te word "$Rev: " 
    char *secondSpaceInVersion = strchr(shortVersion,' '); //Find the space after the number
    *secondSpaceInVersion ='\0';//Eliminate anything after the number, by zeroing the space
    printf("\t \n\cropslices version: 1.0.%s \n\ ",shortVersion);
  printf("USAGE: cropslices <input_file> <output_file>\n\
\t -v <int>            : image size for x and y dimenions (default: 256)\n\
\t -c <int>,<int>      : starting slice (can be negative), ending slice (can be bigger than total slice number in the input image)\n\
");
  exit(1);
}



int main(int argc,char *argv[])
{
  int   c, num ;
  FILE  *fp;


  num=3;
  if(argc<num)
    show_usage();

  start = 0;
  end   = 0 ;
  image_size=256;
  while((c=getopt(argc-2,argv+2,"c:v:")) != -1)
    {
      switch(c)
	{
	case 'c':
	  sscanf(optarg, "%d,%d", &start, &end) ;
	  break;

	case 'v':
	  sscanf(optarg, "%d", &image_size) ;
	  break;

	default:
	  break;
	}
    }
  printf(" start=%d\n end=%d\n", start, end) ;
  printf(" image_size=%d\n", image_size) ;

  Crop3DImage(argc, argv) ;
  
  return 0;
}

