// holefill.c     Section: 11.5, Hole Filling
//      Copyright 1994, Center for Computer Vision and Visualization,
//      University of Florida.  All rights reserved.


#include "holefill.h"
#include "UcharDI.h"
#include "Nbh.h"
#include "DDTempl.h"
#include "UcharConv.h"


IA_Image<IA_Point<int>,IA_Bit>
holefill( const IA_Image<IA_Point<int>,IA_Bit> & a ) {

    // Create s template.  First construct the associated image.

    IA_Set<IA_Point<int> >  s_ps;  // construct as union of two point sets
    s_ps =
	IA_boxy_pset( IA_Point<int>(0,0), IA_Point<int>(-1,1) )
	|  IA_Set<IA_Point<int> >( IA_Point<int>(0,-1) );

    IA_Image<IA_Point<int>,u_char>
	s_im( s_ps, 8 );  // Most common value

    // Correct the other image values
    s_im[ IA_Point<int>(-1,0) ] = 4;
    s_im[ IA_Point<int>( 0,0) ] = 3;
    s_im[ IA_Point<int>( 0,1) ] = 2;


    // s template created
    IA_DDTemplate<IA_Image<IA_Point<int>, u_char> >
	s( 2, s_im );

    // Create the n neighborhood.

    IA_Neighborhood<IA_Point<int>,IA_Point<int> >
	n( 2,
	   IA_boxy_pset( IA_Point<int>(-1,0), IA_Point<int>(1,0) )
	   |  IA_boxy_pset( IA_Point<int>(0,-1), IA_Point<int>(0,1) )
	   );


    IA_Image<IA_Point<int>,u_char>
	udi_a = a,                 // a as an UDI
	b = a,                     // b initialized with a\'s value
	c(a.domain(), u_char(0));  // c is zero valued image

    IA_Set<u_char> hfSet( 14, 22 );

    while (b != c) {
	c = b;
	b += IA_Image<IA_Point<int>,u_char>(
	    chi_contains( linear_product(b,s), hfSet ) );
    }

    c = 0;   // Zero  c  out again
    while ( b != c) {
	c = b;
	b = max( min(b,n), udi_a );
    }

    return to_bit( b );
}
