/*******************************************************************/
/* bb.c extract a bounding box of image content			    */
/*******************************************************************/

#include "VisXV4.h"           /* VisionX structure include file    */
#include "Vutil.h"            /* VisionX utility header files      */
VisXfile_t *VXin,             /* input file structure              */
           *VXout;            /* output file structure             */
VisXelem_t *VXlist;           /* VisionX data structure            */
VisXelem_t *VXptr;            /* VisionX pixel data pointer        */
VXparam_t par[] =             /* command line structure            */
{
{    "if=",    0,   " input file  vtemp: local max filter "},
{    "of=",    0,   " output file "},
{     0,       0,   0}  /* list termination */
};
#define  IVAL   par[0].val
#define  OVAL   par[1].val

VisXimage_t im;                     /* i/o image structure          */
VisXimage_t tm;                     /* temp image structure         */

main(argc, argv)
int argc;
char *argv[];
{
  int i, j;                 /* index counters               */
  float bbx[4];
  unsigned int x_start, x_end, y_start, y_end;
  VXparse(&argc, &argv, par);       /* parse the command line       */
  VXin  = VXopen(IVAL, 0);          /* open input file              */
  VXout = VXopen(OVAL, 1);          /* open the output file         */
  VXlist = VXread(VXin);            /* read file                    */
  if (VXNIL != (VXptr = VXfind(VXlist, VX_PBYTE))){ /* find image */
     VXsetimage(&im, VXptr, VXin);  /* initialize input structure   */

     // find range of x and y values
     x_start = ~0;
     x_end = 0;
     y_start = ~0;
     y_end = 0;
     for (i = im.ylo ; i <= im.yhi ; i++)
        for (j = im.xlo; j <= im.xhi; j++) {
          if (im.u[i][j]) {
            if (i < x_start) x_start = i;
            if (i > x_end) x_end = i;
            if (j < y_start) y_start = j;
            if (j > y_end) y_end = j;
          }
        }

     // determine bounding box, if it exists
     if (x_start == ~0 || x_end < x_start || y_start == ~0 || y_end < y_start) {
        fprintf(stderr, "ir: unable to find bounding box\n");
        exit(-1);
     }

     // size of box
     i = x_end - x_start + 1;
     j = y_end - y_start + 1;
    
     // create a new image
     bbx[0] = 0;
     bbx[1] = j;
     bbx[2] = 0;
     bbx[3] = i;
     VXmakeimage(&tm, VX_PBYTE, bbx, 1);

     // copy image contents
     for (i = x_start; i <= x_end; i++) {
       for (j = y_start; j <= y_end; j++) {
         tm.u[i - x_start][j - y_start] = im.u[i][j];
       }
     }


     VXwrite(VXout, tm.list);     /* write data                   */
  }else{
     fprintf(stderr, "ir: no byte image data in input file\n");
     exit(-1);
  }
  VXclose(VXin);                  /* close files                  */
  VXclose(VXout);
  exit(0);
}
