// Set all the start flags to 1
flag1_start = 1; flag2_start = 1; flag3_start = 1; flag4_start = 1;
flag1_end = 0; flag2_end = 0; flag3_end = 0; flag4_end = 0;
// Write the intermediate files

inter_5.open("V_inter_5.m", ios::out);
inter_6.open("V_inter_6.m", ios::out);
inter_7.open("V_inter_7.m", ios::out);

for (i=0; i<Nv; i++){
	if (V_slave_id[i] == 5) {
		inter_5 << Vx[i] << endl << Vy[i] << endl << Vz[i] << endl;
	}
	else if (V_slave_id[i] == 6) {
		inter_6 << Vx[i] << endl << Vy[i] << endl << Vz[i] << endl;
	}
	else if (V_slave_id[i] == 7) {
		inter_7 << Vx[i] << endl << Vy[i] << endl << Vz[i] << endl;
	}
	
}
inter_5.close();
inter_6.close();
inter_7.close();
		
// Set all end flags to 0 
file_flag1_end_out.open("flag1_end.m", ios::out);
file_flag1_end_out << flag1_end << endl;
file_flag1_end_out.close();
		
file_flag2_end_out.open("flag2_end.m", ios::out);
file_flag2_end_out << flag2_end << endl;
file_flag2_end_out.close();
		
file_flag3_end_out.open("flag3_end.m", ios::out);
file_flag3_end_out << flag3_end << endl;
file_flag3_end_out.close();
		
file_flag4_end_out.open("flag4_end.m", ios::out);
file_flag4_end_out << flag4_end << endl;
file_flag4_end_out.close();

// Set all start flags to 1 
file_flag1_start_out.open("flag1_start.m", ios::out);
file_flag1_start_out << flag1_start << endl;
file_flag1_start_out.close();

file_flag2_start_out.open("flag2_start.m", ios::out);
file_flag2_start_out << flag2_start << endl;
file_flag2_start_out.close();

file_flag3_start_out.open("flag3_start.m", ios::out);
file_flag3_start_out << flag3_start << endl;
file_flag3_start_out.close();

file_flag4_start_out.open("flag4_start.m", ios::out);
file_flag4_start_out << flag4_start << endl;
file_flag4_start_out.close();


// Loop until all the end flags are 1
while (1) {
// Load and check all the end flags
	
	file_flag1_end_in.open("flag1_end.m", ios::in);
	file_flag1_end_in >> flag1_end;
	file_flag1_end_in.close();
	
	file_flag2_end_in.open("flag2_end.m", ios::in);
	file_flag2_end_in >> flag2_end;
	file_flag2_end_in.close();
	
	file_flag3_end_in.open("flag3_end.m", ios::in);
	file_flag3_end_in >> flag3_end;
	file_flag3_end_in.close();
	
	file_flag4_end_in.open("flag4_end.m", ios::in);
	file_flag4_end_in >> flag4_end;
	file_flag4_end_in.close();
	
	cout << "The flags are [" << flag1_end << ", " << flag2_end << ", " << flag3_end << ", " << flag4_end << "]" << endl;
	sleep(1);
	cout << "still waiting for the flags to change" << endl;
	
	// If all end flags are 1 then exit the loop
	if (flag1_end == 1 && flag2_end == 1 && flag3_end == 1 && flag4_end == 1) {
		break;
	}
	
}
	cout << "The flags are [" << flag1_end << ", " << flag2_end << ", " << flag3_end << ", " << flag4_end << "]" << endl;
	cout << "Loop exited" << endl;




