//hàm đọc ngày thay fout = fin á.....
// Find exactly by known day month year
//
// http://en.wikipedia.org/wiki/Julian_day#Calculation
//
int DayOfWeek(Date d1) {
	// Sunday - 8
	int JMD;
	JMD = (d1.day + ((153 * (d1.month + 12 * ((14 - d1.month) / 12) - 3) + 2) / 5) +
		(365 * (d1.year + 4800 - ((14 - d1.month) / 12))) +
		((d1.year + 4800 - ((14 - d1.month) / 12)) / 4) -
		((d1.year + 4800 - ((14 - d1.month) / 12)) / 100) +
		((d1.year + 4800 - ((14 - d1.month) / 12)) / 400) - 32045) % 7; 
	int weekday[] = { 2,
	  3,
	  4,
	  5,
	  6,
	  7,
	  8 };
	return weekday[JMD];
}
bool LeapYear(Date d1)
{
	// If the number of years is divisible by 400 and not divisible by 100
	// If the number of years is divisible by 400,
	// That's a leap year
	if ((d1.year % 4 == 0 && d1.year % 100 != 0) || (d1.year % 400 == 0)) 
		return true;
	return false;
}

//Write Attendance
void WriteAttendance(ofstream& fout, int d, Date d1, Date d2, Time t1, Time t2) {
	int distance;

	// See the distance to the date to be considered 
	if (DayOfWeek(d1) <= d)
		distance = d - DayOfWeek(d1);
	else distance = 8 - DayOfWeek(d1) + d - 1;
	// Move to the date in considered
	NextDays(d1, distance);
	while (CompareDay(d1, d2) <= 0)   //Use loop to compare 2 times
	{
		WriteDay(fout, d1, t1, t2);
		NextDays(d1, 7);
	}
}


void NextDays(Date& d1, int distance)
{
	int Mon[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
	// Check Leap Year 
	if (LeapYear(d1))
		Mon[1] = 29; 
	else Mon[1] = 28;
	// Attach a temporary variable consider day
	int temp = d1.day + distance;

	// If temp > day of month 
	while (temp > Mon[d1.month - 1])
	{
		temp = temp - Mon[d1.month - 1];
		d1.month++;
		if (d1.month == 13)
		{
			d1.month = 1;
			d1.year++;
			if (LeapYear(d1)) Mon[1] = 29; else Mon[1] = 28;
		}
	}
	d1.day = temp;  
}
int CompareDay(Date d1, Date d2)
{
	if (d1.year != d2.year)
	{
		if (d1.year < d2.year) return -1;
		else return 1;
	}
	else if (d1.month != d2.month)
	{
		if (d1.month < d2.month) return -1;
		else return 1;
	}
	else {
		if (d1.day < d2.day) return -1;
		else if (d1.day > d2.day) return 1;
		else return 0;
	}
}
void WriteDay(ofstream& fout, Date d1, Time t1, Time t2)
{
	fout << d1.year << " " << (d1.month < 10 ? "0" : "") << d1.month << " " << (d1.day < 10 ? "0" : "") << d1.day << " " << t1.hour << " " << (t1.minute < 10 ? "0" : "") << t1.minute << " " << t2.hour << " " << (t2.minute < 10 ? "0" : "") << t2.minute << " " << -1 << endl;
}