/*
    module: gasp.c

    The "last_gasp" heuristic computes the reduction of each cube in
    the cover (without replacement) and then performs an expansion of
    these cubes.  The cubes which expand to cover some other cube are
    added to the original cover and irredundant finds a minimal subset.

    If one of the reduced cubes expands to cover some other reduced
    cube, then the new prime thus generated is a candidate for reducing
    the size of the cover.

    super_gasp is a variation on this strategy which extracts a minimal
    subset from the set of all prime implicants which cover all
    maximally reduced cubes.
*/

#include "espresso.h"


/*
 *  reduce_gasp -- compute the maximal reduction of each cube of F
 *
 *  If a cube does not reduce, it remains prime; otherwise, it is marked
 *  as nonprime.   If the cube is redundant (should NEVER happen here) we
 *  just crap out ...
 *
 *  A cover with all of the cubes of F is returned.  Those that did
 *  reduce are marked "NONPRIME"; those that reduced are marked "PRIME".
 *  The cubes are in the same order as in F.
 */
/** MM: pridana kontrola parametrov, ktore NEdealokuje */
/** MM: chyba cez NULL; inak vrati novu strukturu */
static pcover reduce_gasp(pset_family F, pset_family D)
{
    pcube p, last, cunder, *FD;
    pcover G;
    
    if ( (F==NULL) || (D==NULL) ) return NULL; /** MM: ak chyba parametrov */

    G = new_cover(F->count);
    if (G==NULL) return NULL;
    FD = cube2list(F, D);
    if (FD==NULL) {
        sf_free(G);
        return NULL; /** MM: ak chyba alokacie */
    }

    /* Reduce cubes of F without replacement */
    foreach_set(F, last, p) {
    	cunder = reduce_cube(FD, p);
    	if (setp_empty(cunder)) { /** MM: ak fatal */ 
    	    fatal2("empty reduction in reduce_gasp, shouldn't happen");
    	    free_cube(cunder);
    	    free_cubelist(FD);
    	    sf_free(G);
    	    return NULL;
    	} else if (setp_equal(cunder, p)) {
    	    SET(cunder, PRIME);			/* just to make sure */
    	    G = sf_addset(G, p);		/* it did not reduce ... */
    	} else {
    	    RESET(cunder, PRIME);		/* it reduced ... */
    	    G = sf_addset(G, cunder);
    	}
    	if (debug & GASP) {
    	    if (debugoutput!=NULL) fprintf(debugoutput, "REDUCE_GASP: %s reduced to %s\n", pc1(p), pc2(cunder));
    	}
    	free_cube(cunder);
    }

    free_cubelist(FD);
    return G;
}

/*
 *  expand_gasp -- expand each nonprime cube of F into a prime implicant
 *
 *  The gasp strategy differs in that only those cubes which expand to
 *  cover some other cube are saved; also, all cubes are expanded
 *  regardless of whether they become covered or not.
 */

/** MM: pri chybe vrati NULL; inak vrati novu strukturu */
/** MM: kontroluje expand1_gasp a expand */
pcover expand_gasp(pset_family F, pset_family D, pset_family R, pset_family Foriginal)
{
    int c1index, tmp;
    pcover G;

    /* Try to expand each nonprime and noncovered cube */
    G = new_cover(10);
    for(c1index = 0; c1index < F->count; c1index++) {
    	tmp = expand1_gasp(F, D, R, Foriginal, c1index, &G);
    	if (tmp==-1){
            sf_free(G);
            return NULL;
        }
    }
    G = sf_dupl(G);
    G = expand(G, R, /*nonsparse*/ FALSE3);	/* Make them prime ! */
    return G; /** MM: ak chyba v expand, tak si ju musi osetrit volajuci */
}



/*
 *  expand1 -- Expand a single cube against the OFF-set, using the gasp strategy
 */
/** MM: int na kontrolu chyby; -1 pri chybe */
/** MM: kontroluje essen_parts */
int expand1_gasp(pset_family F, pset_family D, pset_family R, pset_family Foriginal, int c1index, pset_family *G)
         		/* reduced cubes of ON-set */
         		/* DC-set */
         		/* OFF-set */
                 	/* ON-set before reduction (same order as F) */
            		/* which index of F (or Freduced) to be checked */
          
{
    register int c2index, tmp;
    register pcube p, last, c2under;
    pcube RAISE, FREESET, temp, *FD, c2essential;
    pcover F1;

    if (debug & EXPAND1) {
    	if (debugoutput!=NULL) fprintf(debugoutput, "\nEXPAND1_GASP:    \t%s\n", pc1(GETSET(F, c1index)));
    }

    RAISE = new_cube();
    FREESET = new_cube();
    temp = new_cube();

    /* Initialize the OFF-set */
    R->active_count = R->count;
    foreach_set(R, last, p) {
    	SET(p, ACTIVE);
    }
    /* Initialize the reduced ON-set, all nonprime cubes become active */
    F->active_count = F->count;
    foreachi_set(F, c2index, c2under) {
    	if (c1index == c2index || TESTP(c2under, PRIME)) {
    	    F->active_count--;
    	    RESET(c2under, ACTIVE);
    	} else {
    	    SET(c2under, ACTIVE);
    	}
    }

    /* Initialize the raising and unassigned sets */
    (void) set_copy(RAISE, GETSET(F, c1index));
    (void) set_diff(FREESET, cube->fullset, RAISE);

    /* Determine parts which must be lowered */
    tmp = essen_parts(R, F, RAISE, FREESET);
    if (tmp==-1){ /** MM: ak chyba v essen_parts */ 
        free_cube(RAISE);
        free_cube(FREESET);
        free_cube(temp);
        return -1;
    }

    /* Determine parts which can always be raised */
    essen_raising(R, RAISE, FREESET);

    /* See which, if any, of the reduced cubes we can cover */
    foreachi_set(F, c2index, c2under) {
    	if (TESTP(c2under, ACTIVE)) {
    	    /* See if this cube can be covered by an expansion */
    	    if (setp_implies(c2under, RAISE) ||
    	      feasibly_covered(R, c2under, RAISE, temp)) {
        		
        		/* See if c1under can expanded to cover c2 reduced against
        		 * (F - c1) u c1under; if so, c2 can definitely be removed !
        		 */
        
        		/* Copy F and replace c1 with c1under */
        		F1 = sf_save(Foriginal);
        		(void) set_copy(GETSET(F1, c1index), GETSET(F, c1index));
        
        		/* Reduce c2 against ((F - c1) u c1under) */
        		FD = cube2list(F1, D);
        		c2essential = reduce_cube(FD, GETSET(F1, c2index));
        		free_cubelist(FD);
        		sf_free(F1);
        
        		/* See if c2essential is covered by an expansion of c1under */
        		if (feasibly_covered(R, c2essential, RAISE, temp)) {
        		    (void) set_or(temp, RAISE, c2essential);
        		    RESET(temp, PRIME);		/* cube not prime */
        		    *G = sf_addset(*G, temp);
        		}
        		set_free(c2essential);
    	    }
    	}
    }

    free_cube(RAISE);
    free_cube(FREESET);
    free_cube(temp);
    
    return 0;
}

/* irred_gasp -- Add new primes to F and find an irredundant subset */
/** MM: modifikuje F, pri chybe ho dealokuje */
pcover irred_gasp(pset_family F, pset_family D, pset_family G)
                                /* G is disposed of */
{
    if (G->count != 0)
    	F = irredundant(sf_append(F, G), D); /** MM: hodnotu musi skontrolovat volajuci */
    else
    	free_cover(G);
    return F;
}


/* last_gasp */
/** MM: osetrene reduce_gasp, expand_gasp a irred_gasp; chyba cez NULL */
/** F dealokuje len pri chybe, normalne vracia upravene F */
pcover last_gasp(pset_family F, pset_family D, pset_family R, cost_t *cost)
{
    pcover G, G1;

    EXECUTE(G = reduce_gasp(F, D), GREDUCE_TIME, G, *cost);
    if (G==NULL) { /** MM: ak chyba v reduce_gasp */
        sf_free(F); /** MM: musi sa uvolnit, inak sa o tom volajuci nedozvie/strati referenciu */
        return NULL; 
    }
    EXECUTE(G1 = expand_gasp(G, D, R, F), GEXPAND_TIME, G1, *cost);
    free_cover(G);
    if (G1==NULL){
        sf_free(F); /** MM: musi sa uvolnit, inak sa o tom volajuci nedozvie/strati referenciu */
        return NULL;
    }
    EXECUTE(F = irred_gasp(F, D, G1), GIRRED_TIME, F, *cost); /** MM: pri chybe dealokuje F a bude mat hodnotu NULL */
    return F; /** MM: validnost musi skontrolovat volajuci */
}


/* super_gasp */
/** MM: osetrene reduce_gasp, all_primes a irredundant; chyba cez NULL */
/** F dealokuje len pri chybe, normalne vracia upravene F */
pcover super_gasp(pset_family F, pset_family D, pset_family R, cost_t *cost)
{
    pcover G, G1;

    EXECUTE(G = reduce_gasp(F, D), GREDUCE_TIME, G, *cost);
    if (G==NULL) { /** MM: ak chyba v reduce_gasp */
        sf_free(F); /** MM: musi sa uvolnit, inak sa o tom volajuci nedozvie/strati referenciu */
        return NULL; 
    }
    EXECUTE(G1 = all_primes(G, R), GEXPAND_TIME, G1, *cost);
    free_cover(G);
    if (G1==NULL){ /** MM: ak chyba all_primes */
        sf_free(F);
        return NULL;
    }
    EXEC(G = sf_dupl(sf_append(F, G1)), "NEWPRIMES", G);
    EXECUTE(F = irredundant(G, D), IRRED_TIME, F, *cost); /** MM: validnost musi skontrolovat volajuci */
    return F;
}
