#include <cstdio>
#include <cstdlib>
#include <assert.h>

#include "circuit.h"

int main(int args, char* argv[]) {

    if(args != 2) {
        printf("usage: ./atpg <XXX.bench>\n");
        exit(1);
    }

    srand(19260817);

    Circuit* circuit = new Circuit();

    printf("parsing file %s ...", argv[1]);
    circuit->parse_from_file(argv[1]);
    circuit->init_stems();
    circuit->init_topo_index();
    printf(" Done.\n");

    printf("====== Circuit Statistics ====== \n");
    printf("PI:\t%ld\n", circuit->PIs.size());
    printf("PO:\t%ld\n", circuit->POs.size());
    printf("Gate:\t%ld\n", circuit->name2gate.size());
    printf("Stem:\t%ld\n", circuit->stems.size());
    printf("================================ \n");

    std::unordered_set<Fault*> faults;

    // init faults
    for(auto g : circuit->gates) {
        faults.insert(new Fault(g, Fault::SA0));
        faults.insert(new Fault(g, Fault::SA1));
    }

    while(true) {
        bool ls = circuit->local_search(faults);
        bool is_valid = circuit->is_valid_circuit();
        printf("checking valid circuit ...");
        printf(" result: %d.\n", is_valid);
        if(!ls) break;
        if(!is_valid) break; 
        if(faults.size() == 0) break;

        //circuit->print_gates();
        //break;
    }

    //printf("[final] flip: %d, stem: %d, fault:%d\n", circuit->flip_total_weight, circuit->stem_total_weight, circuit->fault_total_weight);

    return 0;
}