 /*
  * Khoros: $Id: vkmeans.c,v 1.2 1991/12/18 09:32:15 dkhoros Exp $
  */

#if !defined(lint) && !defined(SABER)
static char rcsid[] = "Khoros: $Id: vkmeans.c,v 1.2 1991/12/18 09:32:15 dkhoros Exp $";
#endif

 /*
  * $Log: vkmeans.c,v $
 * Revision 1.2  1991/12/18  09:32:15  dkhoros
 * HellPatch3
 *
  */

/*
 *----------------------------------------------------------------------
 *
 * Copyright 1991, University of New Mexico.  All rights reserved.
 * Permission to copy and modify this software and its documen-
 * tation only for internal use in your organization is hereby
 * granted, provided that this notice is retained thereon and
 * on all copies.  UNM makes no representations as to the sui-
 * tability and operability of this software for any purpose.
 * It is provided "as is" without express or implied warranty.
 * 
 * UNM DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FIT-
 * NESS.  IN NO EVENT SHALL UNM BE LIABLE FOR ANY SPECIAL,
 * INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY OTHER DAMAGES WHAT-
 * SOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
 * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PER-
 * FORMANCE OF THIS SOFTWARE.
 * 
 * No other rights, including, for example, the right to redis-
 * tribute this software and its documentation or the right to
 * prepare derivative works, are granted unless specifically
 * provided in a separate license agreement.
 *---------------------------------------------------------------------
 */

#include "unmcopyright.h"        /* Copyright 1991 by UNM */

/*>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
 >>>>
 >>>>         File Name: vkmeans.c
 >>>>
 >>>>      Program Name: vkmeans
 >>>>
 >>>>      Program Desc: 
 >>>>	
 >>>>	Performs the kmeans clustering algorithm on an image
 >>>>	
 >>>>	

 >>>>            Author: Tom Sauer, Charlie Gage
 >>>>
 >>>> Date Last Updated: Wed Dec  4 14:44:07 1991
 >>>>
 >>>>          Routines: main- the main program for vkmeans
 >>>> 		 gw_usage - gives usage of the program
 >>>> 		 gw_args  - gets arguments of program from command line
 >>>>
 >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>   <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<*/


#include "vkmeans.h"


/****************************************************************
 *
 * Routine Name:  main program for vkmeans
 *
 *       Input:  
 *         -i1  input image 
 *         -o1  output cluster number image 
 *         -f2  output file for kmeans statistics 
 *
 *
 *         [-o2] output image for cluster centers
 *         [-o3] output image for variance
 *         [-m] Output Image Map Enable
 *         [-n] specifies maximum number of iterations (default = 100000)  (1 < value < 100000)
 *         [-k] specifies number of clusters (default = 2)  (value > 0)
 *         [-b]  specifies the border width in pixels (default = 0)  (value >= 0)
 *
 *         [-c  if Yes use First K Vectors As Cluster Centers   -OR-
 *          -f1  input ASCII file for x-y coordinates of cluster centers  -OR-
 *          -i2  input image cluster center values   ]
 *
 *
 *
 ****************************************************************/


main(argc, argv)
int argc;
char *argv[];
{

/* -main_variable_list */
struct xvimage *image, *image1, *cc_img, *readimage(), *createimage();
struct xvimage *sqd_image;
FILE *printdev1, *printdev2;
char *dummy = '\0';
int **init_cluster;
int i, x, y, im_size;
/* -main_variable_list_end */

	program = VStrcpy(argv[0]);
	ac = argc;
	av = argv;

	khoros_init();

	gw_get_args();

/* -main_before_lib_call */
if (check_args()) exit(1);
/* -main_before_lib_call_end */

/* -main_library_call */
READINPUT (image);
CHECKINPUT (program, image);

   /* Allocate space for initial cluster centers */

   init_cluster = (int **) malloc(vkmeans->k_int * sizeof(int));
    if (init_cluster == NULL) {
             (void) fprintf(stderr, "vkmeans: No space for init_clusters - malloc failed!\\n");
              exit(1);
    }
    for (i = 0 ; i < vkmeans->k_int ; i++) {
        init_cluster[i] = (int *) malloc(sizeof(int) * 2 );
        if (init_cluster[i] == NULL) {
            (void) fprintf(stderr, "vkmeans: No space for image - malloc failed!\\n");
            exit(1);
         }
     }

      /* check to make sure the user has not entered more clusters
         than there are vectors */
    im_size = (image->row_size - (2 * vkmeans->b_int)) * (image->col_size - (2 * vkmeans->b_int));
    if ( vkmeans->k_int > im_size) {
       (void) fprintf(stderr, "vkmeans: Too many clusters\\n");
       (void) fprintf(stderr, "vkmeans: Requested number of clusters = %d\\n", vkmeans->k_int);
       (void) fprintf(stderr, "vkmeans: Maximum number of clusters = %d\\n", im_size);
       exit(1);
    }

   /* Read in cluster center image as input for initial cluster centers */
   if (vkmeans->i2_flag)
   {
    cc_img = readimage(vkmeans->i2_file);
    if(cc_img == NULL){
     (void) fprintf(stderr,"vkmeans: Cluster Center Image could not be read\n");
     exit(1);
    }

    /* Make sure number of bands in cluster center image matches the
        the number of bands in the input image.  */
    CHECKINPUT(program, cc_img);
    (void) match_num_bands(program,image,cc_img,TRUE);

    /* Check number of cluster centers in cluster center image against
         the number of desired clusters, and inform user of mismatch. */
    if ((cc_img->row_size * cc_img->col_size) != vkmeans->k_int)
    {
      (void) fprintf(stderr, "vkmeans: Number of Cluster Centers in Cluster Center Image\\n");
      (void) fprintf(stderr,"must match number of desired clusters.\\n");
      (void) fprintf(stderr, "vkmeans: Number of Cluster Centers in Cluster Center Image = %d\\n", cc_img->row_size * cc_img->col_size);
      (void) fprintf(stderr,"Number of desired clusters = %d\\n", vkmeans->k_int);
      exit(1);
    }
   }
   else if ( vkmeans->f1_flag)  /* user specified cluster center positions */
   {
      if (! vread_ascii(vkmeans->f1_file, &printdev1))
      {
         (void) fprintf(stderr, "vkmeans:  Can't open ascii input file: \\n");
         exit(1);
      }

       for (i = 0 ; i < vkmeans->k_int ; i++) {
         fscanf(printdev1, "%d", &init_cluster[i][0]);
                /* check to make sure the x-y coordinate is inside the
                   borders */
         if ( init_cluster[i][0] < vkmeans->b_int || init_cluster[i][0] > (image->row_size - vkmeans->b_int)) {
            (void) fprintf(stderr, "vkmeans: x-coordinate in 'file' %s, line %d is out of range\\n", vkmeans->f1_file, i);
            exit(1);
         }

         fscanf(printdev1, "%d", &init_cluster[i][1]);
                /* check to make sure the x-y coordinate is inside the
                   borders */
         if ( init_cluster[i][1] < vkmeans->b_int || init_cluster[i][1] > (image->col_size - vkmeans->b_int)) {
             (void) fprintf(stderr, "vkmeans: y-coordinate in 'file' %s, line %d is out of range\\n", vkmeans->f1_file, i);
             exit(1);
         }
         init_cluster[i][0] = init_cluster[i][0] - vkmeans->b_int;
         init_cluster[i][1] = init_cluster[i][1] - vkmeans->b_int;
       }
       fclose(printdev1);
   }
   else                 /* use first K vectors as initial cluster centers */
   {
     x = vkmeans->b_int;
     y = vkmeans->b_int;
     for ( i = 0 ; i < vkmeans->k_int ; i++ )
     {
         init_cluster[i][0] = x++;
         init_cluster[i][1] = y;
         if ( x == image->row_size - vkmeans->b_int) {
            x = vkmeans->b_int;
            y += 1;
         }
     }
   }

/* Open file for K-means statistics */
if (vkmeans->f2_flag) {
   if (! vwrite_ascii(vkmeans->f2_file, &printdev2))
   {
      (void) fprintf(stderr, "vkmeans:  Can't open ascii output file: \\n");
      exit(1);
   }
}
else
  printdev2 = stdout;

/* Allocate space for output image (cluster center band) */
if (vkmeans->o2_flag)
{
    image1 = createimage(1, 
                         vkmeans->k_int, 
                         VFF_TYP_FLOAT, 
                         1, 
                         image->num_data_bands, 
                         dummy, 0, 0, 
                         VFF_MS_NONE, 
                         VFF_MAPTYP_NONE, 
                         VFF_LOC_IMPLICIT, 0);

        if (image1 == NULL)
        {
           (void)fprintf(stderr,"vkmeans: Unable to allocate new image!\\n");
           exit(1);
        }
}

/* Allocate space for output image for the square distance values */
if (vkmeans->o3_flag)
{
    sqd_image = createimage(1, 
                            vkmeans->k_int, 
                            VFF_TYP_FLOAT, 
                            1, 
                            image->num_data_bands, 
                            dummy, 0, 0, 
                            VFF_MS_NONE, 
                            VFF_MAPTYP_NONE, 
                            VFF_LOC_IMPLICIT, 0);
        if (sqd_image == NULL)
        {
           (void)fprintf(stderr,"vkmeans: Unable to allocate new image!\\n");
           exit(1);
        }
}

    /* Call the lib routine for K-means algorithm */
    if(! lvkmeans(image, image1, vkmeans->o2_flag,  sqd_image, vkmeans->o3_flag,
                  vkmeans->n_int, vkmeans->k_int, vkmeans->b_int, init_cluster, 
                  printdev2, vkmeans->i2_flag, vkmeans->m_logic, cc_img))
    {
        (void) fprintf(stderr, "lvkmeans Failed\\n");
        exit(1);
    }
/* -main_library_call_end */

/* -main_after_lib_call */
/* write out the cluster center image and the cluster image */
writeimage(vkmeans->o1_file,image);
if (vkmeans->o2_flag)
writeimage(vkmeans->o2_file,image1);
if (vkmeans->o3_flag)
writeimage(vkmeans->o3_file,sqd_image);
/* -main_after_lib_call_end */


	khoros_close();
}


/****************************************************************
*
* Routine Name:  gw_usage 
*
*
* Purpose:  prints out the usage for vkmeans 
*
* Input:  none 
*
* Output:  none 
*
* Written By:  automatically generated by ghostwriter
*
****************************************************************/


gw_usage()
{
	fprintf(stderr, "vkmeans :\n");
	fprintf(stderr, "\t\n");
	fprintf(stderr, "\tPerforms the kmeans clustering algorithm on an image\n");
	fprintf(stderr, "\t\n");
	fprintf(stderr, "\t\n");

/* -usage_additions */
/* -usage_additions_end */

	fprintf(stderr,"\t-i1  input image  (infile)\n");
	fprintf(stderr,"\t-o1  output cluster number image  (outfile)\n");
	fprintf(stderr,"\t-f2  output file for kmeans statistics  (outfile)\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "\n");
	fprintf(stderr,"\t[-o2]  output image for cluster centers (outfile) [null]\n");
	fprintf(stderr,"\t[-o3]  output image for variance (outfile) [null]\n");
	fprintf(stderr,"\t[-m]  Output Image Map Enable (boolean) [true]\n");
	fprintf(stderr,"\t[-n]  specifies maximum number of iterations (default = 100000) (integer, 1 to 100000) [50000]\n");
	fprintf(stderr,"\t[-k]  specifies number of clusters (default = 2) (integer, > 0) [2]\n");
	fprintf(stderr,"\t[-b]   specifies the border width in pixels (default = 0) (integer, >= 0) [0]\n");
	fprintf(stderr, " \n");
	fprintf(stderr, "\t[ ");
	fprintf(stderr,"-c  if Yes use First K Vectors As Cluster Centers  (boolean) -OR- \n");
	fprintf(stderr,"\t  -f1  input ASCII file for x-y coordinates of cluster centers  (infile) -OR- \n");
	fprintf(stderr,"\t  -i2  input image cluster center values  (infile) ]\n\n");
	fprintf(stderr, "\n");
	fprintf(stderr, "\t[-V] Gives the version for vkmeans\n");
	fprintf(stderr, "\t[-U] Gives the usage for vkmeans\n");
	fprintf(stderr, "\t[-P] Prompts for command line options\n");
	fprintf(stderr, "\t[-A [file1]] Creates the answer file called vkmeans.ans or file1 \n");
	fprintf(stderr, "\t[-a [file1]] Uses vkmeans.ans or file1 as the answer file \n\n\n");

}


/****************************************************************
*
* Routine Name:  gw_getargs 
*
*
* Purpose:  gets arguments off command line for vkmeans
*
* Input:  none 
*
* Output:  none 
*
* Written By:  automatically generated by ghostwriter
*
****************************************************************/


gw_get_args()
{

char	*i1_pstr = 
	"\nEnter: (i1) input image \n        {infile}: "; 
char	*o1_pstr = 
	"\nEnter: (o1) output cluster number image \n        {outfile}: "; 
char	*f2_pstr = 
	"\nEnter: (f2) output file for kmeans statistics \n        {outfile}: "; 
char	*o2_pstr = 
	"\nEnter: (o2) output image for cluster centers \n        {outfile}: "; 
char	*o3_pstr = 
	"\nEnter: (o3) output image for variance \n        {outfile}: "; 
char	*m_pstr = 
	"\nEnter: (m) Output Image Map Enable \n        {boolean, (y/n)  [yes] }: "; 
char	*n_pstr = 
	"\nEnter: (n) specifies maximum number of iterations (default = 100000) \n        {integer, 1 to 100000 [50000] }: "; 
char	*k_pstr = 
	"\nEnter: (k) specifies number of clusters (default = 2) \n        {integer, > 0 [2] }: "; 
char	*b_pstr = 
	"\nEnter: (b)  specifies the border width in pixels (default = 0) \n        {integer, >= 0 [0] }: "; 
char	*c_pstr = 
	"\nEnter: (c) if Yes use First K Vectors As Cluster Centers \n        {boolean, (y/n)  [yes] }: "; 
char	*f1_pstr = 
	"\nEnter: (f1) input ASCII file for x-y coordinates of cluster centers \n        {infile}: "; 
char	*i2_pstr = 
	"\nEnter: (i2) input image cluster center values \n        {infile}: "; 
char  answer_file[512], temp[512];



int	fid = -1,
	error, query, ok, count;
	int prompt_flag = FALSE;

	/*
	 * print version if necessary
	 */
	vgparml(fid, "-V", "noprompt", &query, 0, 0, &error);
	if (error == 0)
	{
	    printf ("\n%s: %s: Version %d.%d\n\n",
	    "vkmeans", RELEASE_NAME, RELEASE_MAJOR, RELEASE_MINOR);
	    exit(1);
	}

	/*
	 * print usage if necessary
	 */
	vgparml(fid, "-U", "noprompt", &query, 0, 0, &error);
	if (error == 0)
	{
	    gw_usage();
	    exit(1);
	}

	/*
	 * see if interactive prompting is desired
	 */
	vgparml(fid, "-P", "noprompt", &query, 0, 0, &error);
	if (error == 0)
	    prompt_flag = TRUE;

	/*
	 * see if answer file is to be used
	 */
	vgparms(fid, "-a", "noprompt", answer_file, 0, 0, &error);
	if (error == 0)
	{
	     if (VStrlen(answer_file) == 0)
		sprintf(answer_file, "vkmeans.ans");
	     while (fid < 0)
	     {
		if ((fid = open(answer_file, O_RDONLY, 0666))== -1)
		{
		    fprintf(stderr, "vkmeans: can't open answer file \"%s\"",
			    answer_file); 
		    fprintf(stderr, "please re-enter: ");
		    (void) gets(answer_file);
		    if (VStrlen(answer_file) == 0)
			sprintf(answer_file, "vkmeans.ans");
		}

	     }

	}

	/*
	 * allocate the vkmeans structure
	 */
	vkmeans = (vkmeans_struct *) 
	       calloc((unsigned)1, (unsigned) sizeof (vkmeans_struct));

	/*
	 * get required arguments for vkmeans
	 */
	if (prompt_flag == TRUE)
	    fprintf(stderr,"\nRequired Arguments:\n\n");

	if (!(vkmeans->i1_flag = vget_infile(fid, prompt_flag,
			"-i1", i1_pstr, &(vkmeans->i1_file))
))
	{
	    if (prompt_flag == TRUE)
	    {
		while(!(vkmeans->i1_flag))
		{
		    fprintf(stderr, "\t\ti1 is required, please re-enter: \n");
		    vkmeans->i1_flag = vget_infile(fid, prompt_flag,
		    "-i1", i1_pstr, &(vkmeans->i1_file))
;

		}
	    }
	    else
	    {
		fprintf(stderr, "Error: '-i1' is a required argument\n");
		gw_usage();
		exit(1);
	    }
	}

	if (!(vkmeans->o1_flag = vget_outfile(fid, prompt_flag,
			"-o1", o1_pstr, &(vkmeans->o1_file))
))
	{
	    if (prompt_flag == TRUE)
	    {
		while(!(vkmeans->o1_flag))
		{
		    fprintf(stderr, "\t\to1 is required, please re-enter: \n");
		    vkmeans->o1_flag = vget_outfile(fid, prompt_flag,
		    "-o1", o1_pstr, &(vkmeans->o1_file))
;

		}
	    }
	    else
	    {
		fprintf(stderr, "Error: '-o1' is a required argument\n");
		gw_usage();
		exit(1);
	    }
	}

	if (!(vkmeans->f2_flag = vget_outfile(fid, prompt_flag,
			"-f2", f2_pstr, &(vkmeans->f2_file))
))
	{
	    if (prompt_flag == TRUE)
	    {
		while(!(vkmeans->f2_flag))
		{
		    fprintf(stderr, "\t\tf2 is required, please re-enter: \n");
		    vkmeans->f2_flag = vget_outfile(fid, prompt_flag,
		    "-f2", f2_pstr, &(vkmeans->f2_file))
;

		}
	    }
	    else
	    {
		fprintf(stderr, "Error: '-f2' is a required argument\n");
		gw_usage();
		exit(1);
	    }
	}

	/*
	 * get optional arguments for vkmeans
	 */
	if (prompt_flag == TRUE)
	   fprintf(stderr,"\nOptional Arguments:\n\n");

	vkmeans->o2_flag = vget_outfile(fid, prompt_flag,
	"-o2", o2_pstr, &(vkmeans->o2_file))
;

	vkmeans->o3_flag = vget_outfile(fid, prompt_flag,
	"-o3", o3_pstr, &(vkmeans->o3_file))
;

	vkmeans->m_flag = vget_logic(fid, prompt_flag,
	"-m", m_pstr, &(vkmeans->m_logic), 1);

	vkmeans->n_flag = vget_int(fid, prompt_flag,
	"-n", n_pstr, &(vkmeans->n_int),
	50000, 1, 100000);

	vkmeans->k_flag = vget_int(fid, prompt_flag,
	"-k", k_pstr, &(vkmeans->k_int),
	2, 2, 2);

	vkmeans->b_flag = vget_int(fid, prompt_flag,
	"-b", b_pstr, &(vkmeans->b_int),
	0, 1, 1);

	/*
	 * get optional mutually exclusive groups for vkmeans
	 */
	if (prompt_flag == TRUE)
	{
		   fprintf(stderr, "\nThe following prompts are mutually exclusive.\n");
		   fprintf(stderr, "\nHit <cr> until the desired prompt appears.\n");
		vkmeans->c_flag = vget_logic(fid, prompt_flag,
		    "-c", c_pstr, &(vkmeans->c_logic), 1);

    		if(!( (vkmeans->c_flag)))
		    vkmeans->f1_flag = vget_infile(fid, prompt_flag,
		    "-f1", f1_pstr, &(vkmeans->f1_file))
;

    		if(!( (vkmeans->c_flag)|| 
		     (vkmeans->f1_flag)))
		    vkmeans->i2_flag = vget_infile(fid, prompt_flag,
		    "-i2", i2_pstr, &(vkmeans->i2_file))
;

		   fprintf(stderr, "\n ------\n");
	}
	else
	{
		count = 0;
		if(vkmeans->c_flag = vget_logic(fid, prompt_flag,
		    "-c", c_pstr, &(vkmeans->c_logic), 1))
		    count++;

		if(vkmeans->f1_flag = vget_infile(fid, prompt_flag,
		    "-f1", f1_pstr, &(vkmeans->f1_file))
)
		    count++;

		if(vkmeans->i2_flag = vget_infile(fid, prompt_flag,
		    "-i2", i2_pstr, &(vkmeans->i2_file))
)
		    count++;

		if (count > 1)
		{
		    fprintf(stderr, "Error: You may specify ONLY ONE of :\n");
		    fprintf(stderr, " -c  -f1  -i2 \n");
		    gw_usage();
		    exit(1);
		}

	}


}



