#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <math.h>
#include <strings.h>
#include <mvcd.h>
#include <cres.h>


int  x_size, y_size ;


void ChangeLineValue(int argc, char *argv[], int x_size, int y_size, int ValueOrig, int ValueCurrent)
{
  unsigned char ***src, ***outp ;
  int  i,j,k, status, z_size ;
  FILE *fp;

  fp=myopen(argv[1],"r"); printf("%s\n", argv[1]) ;
  fseek(fp,0,SEEK_END);
  z_size=ftell(fp)/(x_size*y_size);  printf("z_size=%d\n", z_size) ;
  rewind(fp);

  /* apply for memory */ 
  src  = UCalloc3d(x_size, y_size, z_size);
  outp = UCalloc3d(x_size, y_size, z_size);

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


  /* reset ... */
  for(k=0;k<z_size;k++)
    for(i=0; i<x_size; i++)
      for(j=0; j<y_size; j++)
	outp[k][i][j] = src[k][i][j] ;
	

  /* searching  */
  status = 0 ;
  for(k=0;k<z_size;k++)
    for(i=0; i<x_size; i++)
      for(j=0; j<y_size; j++)
	if(src[k][i][j]==ValueOrig)  
	  {
	    outp[k][i][j]=ValueCurrent ;
	    status ++ ;
	  }

  /* write the smoothed image */
  if(status>0) 
    {
      printf("Write file!\n") ;
      fp=myopen(argv[2],"w");
      for(k=0;k<z_size;k++)
	for(i=0;i<x_size;i++)
	  fwrite(outp[k][i],1,y_size,fp);
      fclose(fp);
    }
  else
    printf("No operation on file!\n") ;
  
  /* free */
  UCfree3d(src, z_size, x_size) ;
  UCfree3d(outp, z_size, x_size) ;
}



void show_usage()
{
  printf("USAGE: ChangeLineValueInImg <src_file> <out_file>\n\
\t -s <int>               : zoom image (1.0)\n\
\t -x <int>               : x dimension size (256)\n\
\t -y <int>               : y dimension size (256)\n\
\t -o <int>               : current line value\n\
\t -c <int>               : required line value\n\
");
  exit(1);
}



int main(int argc,char *argv[])
{
  int   c, num ;
  float zoomm ;
  int ValueOrig, ValueCurrent ;

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


  /* functions and their parameters */
  zoomm = 1.0 ;
  x_size=256 ;
  y_size=256 ;
  ValueOrig = -1 ;
  ValueCurrent = 0 ;

  while((c=getopt(argc-2,argv+2,"s:x:y:o:c:")) != -1)
    {
      switch(c)
	{
	case 's':
	  zoomm=atof(optarg);
	  break;

	case 'x':
	  x_size=atoi(optarg);
	  break;

	case 'y':
	  y_size=atoi(optarg);
	  break;

	case 'o':
	  ValueOrig=atoi(optarg);
	  break;

	case 'c':
	  ValueCurrent=atoi(optarg);
	  break;


	default:
	  break;
	}
    }

  printf(" zoom=%f\n x-size=%d\n y-size=%d\n ValueOrig=%d\n ValueCurrent=%d\n\n", zoomm, x_size, y_size, ValueOrig, ValueCurrent) ;

  ChangeLineValue(argc, argv, x_size, y_size, ValueOrig, ValueCurrent) ;

  return 0;
}

