+int distribute_jobs(t_event *event,void *allineed) {
+
+ t_net *net;
+ t_list *c_list,*g_list,*job;
+ int count_j,count_c,min;
+ t_job *j;
+ t_client *c;
+ unsigned char data;
+ d3_lattice d3l;
+ unsigned int addr[4];
+
+ memcpy(addr,allineed,4*sizeof(unsigned int));
+
+ net=(t_net *)addr[0];
+ c_list=(t_list *)addr[1];
+ g_list=(t_list *)addr[2];
+ job=(t_list *)addr[3];
+
+ list_reset(job);
+ list_reset(c_list);
+
+ count_j=0;
+ count_c=0;
+
+ if((c_list->current==NULL)||(job->current==NULL)) return 2;
+
+ j=(t_job *)job->current->data;
+ c=(t_client *)c_list->current->data;
+ if(j->status==IN_QUEUE) count_j++;
+ if(c->status==IDLE) count_c++;
+
+ while(list_next(job)!=L_NO_NEXT_ELEMENT) {
+ j=(t_job *)job->current->data;
+ if(j->status==IN_QUEUE) count_j++;
+ }
+ while(list_next(c_list)!=L_NO_NEXT_ELEMENT) {
+ c=(t_client *)c_list->current->data;
+ if(c->status==IDLE) count_c++;
+ }
+
+ min=(count_c<count_j)?count_c:count_j;
+
+ if(min!=0) {
+ printf("d: distributing jobs ...\n");
+ printf("%d queued jobs, %d idle clients\n\n",count_j,count_c);
+ }
+
+ list_reset(job);
+ list_reset(c_list);
+
+ while(min) {
+ j=(t_job *)job->current->data;
+ c=(t_client *)c_list->current->data;
+ while(c->status!=IDLE) {
+ list_next(c_list);
+ c=(t_client *)c_list->current->data;
+ }
+ while(j->status!=IN_QUEUE) {
+ list_next(job);
+ j=(t_job *)job->current->data;
+ }
+
+ /* direct current job to current client */
+ if(j->step==0) data=NLSOP_NJOB;
+ else data=NLSOP_CJOB;
+
+ c->status=WORK;
+ j->channel=c->channel;
+ j->status=IN_WORK;
+
+ d3l.max_x=j->x;
+ d3l.max_y=j->y;
+ d3l.max_z=j->z;
+
+ network_send_chan(net,c->channel,&data,sizeof(unsigned char));
+ network_send_chan(net,c->channel,(unsigned char *)&d3l,sizeof(d3_lattice));
+ network_send_chan(net,c->channel,(unsigned char *)&(j->info),sizeof(info));
+
+ if(data==NLSOP_CJOB) {
+ network_send_chan(net,c->channel,j->ac,j->size*sizeof(unsigned char));
+ network_receive_chan(net,c->channel,&data,sizeof(unsigned char));
+ network_send_chan(net,c->channel,(unsigned char *)&(j->cc),
+ j->size*sizeof(int));
+ network_receive_chan(net,c->channel,&data,sizeof(unsigned char));
+ network_send_chan(net,c->channel,(unsigned char *)&(j->step),sizeof(int));
+ network_receive_chan(net,c->channel,&data,sizeof(unsigned char));
+ }
+
+ --min;
+ list_next(c_list);
+ list_next(job);
+ }
+
+ return 1;
+}
+