#include "manager.h"
#include "CentralLB.h"
#include "converse.h"

CkGroupID manager_group_id;
extern int load_balancer_created;
int group_created;

void handler(char *bit_map)
{
    bit_map += CmiMsgHeaderSizeBytes;
    
    CkPrintf("in handler\n");
    
    for(int i=0; i < CkNumPes() ; i++) 
	CkPrintf("%d, ",bit_map[i]);

    if((CkMyPe() == 0) && (load_balancer_created))
	set_avail_vector(bit_map);
    /*
    CProxy_BitVector_handler gproxy(manager_group_id);

    int num_proc = CkNumPes();
    BitVector *bit_vector = new(&num_proc,0) BitVector;
    for(int i=0; i < CkNumPes() ; i++) 
	bit_vector->vector[i] = bit_map[i];

    bit_vector->n_elements = CkNumPes();
    
    
    if(group_created)
    gproxy.update(bit_vector); 
    */
}
/*
double cputime = 0.0;
double walltime = 0.0;

struct loadData{
    double walltime;
    double utilization;
};
void load_accumulator(...){
    double oldcputime = cputime;
    double oldwalltime = walltime;
    cputime = CmiCpuTimer();
    walltime = CmiWallTimer();

    if(walltime - oldwalltime < 0.5)
	return;

    double intervalUsage = (cputime - oldcputime) * 100 / 
	(walltime - oldwalltime);
    
    CkPrintf("%f  %f\n",  walltime, intervalUsage);
    CcdCallFnAfter(load_accumulator, NULL, 500);
    cputime = CmiCpuTimer();
    walltime = CmiWallTimer();
}
*/
void manager_init(){    
    //    load_accumulator();
    CcsRegisterHandler("set_bitmap", (CmiHandler) handler);
    
    manager_group_id = CProxy_BitVector_handler::ckNew();   
}

BitVector_handler::BitVector_handler(void){
    seq_no = 0;
    
    group_created = 1;
    int num_proc = CkNumPes();
    vector = new char[num_proc];
    
    for(int i = 0; i < num_proc; i++)
	vector[i] = 1;
}

void BitVector_handler::update(BitVector *bit_vector){
    
    int num_proc = bit_vector->n_elements;

    for(int i = 0; i < num_proc; i++){
	vector[i] = bit_vector->vector[i];
	//	CkPrintf("%d ",vector[i]);
    }
	
    CldSetPEBitVector(vector);   
}

void* BitVector::alloc(int mnum, size_t size, int *sizes, int priobits){
    int total_size = size + sizes[0] * sizeof(char);
    
    BitVector *bit_vector = (BitVector*)CkAllocMsg(mnum, total_size, priobits);

    bit_vector->vector = (char *)((char *)bit_vector + sizeof(BitVector));
    
    return (void *)bit_vector;
}

void* BitVector::pack(BitVector *bit_vector){
    return (void *) bit_vector;
}

BitVector* BitVector::unpack(void *buf){
    BitVector *bit_vector = (BitVector*)buf;

    bit_vector->vector = (char*)((char*)bit_vector + sizeof(BitVector));
    return bit_vector;
}


#include "manager.def.h"












