PHP calender: move the column of Sunday to the end

Hi,

this is the calendar script I got it from an online tutorial, it works fine but I want to move the column of Sunday to the end (After the column of Saturday),

<?php
if (!isset($_REQUEST["month"])) $_REQUEST["month"] = date("n");
if (!isset($_REQUEST["year"]))  $_REQUEST["year"]  = date("Y");
	
$month_current = $_REQUEST["month"];
$year_current  = $_REQUEST["year"];
                
$prev_year = $year_current;
$next_year = $year_current;

$month_previous = $month_current-1;
$month_next = $month_current+1;

if ($month_previous == 0 ) 
{
	$month_previous = 12;
	$prev_year = $year_current - 1;
}

if ($month_next == 13 ) 
{
	$month_next = 1;
	$next_year = $year_current + 1;
}

$timestamp = mktime(0,0,0,$month_current,1,$year_current);
$lastdate    = date("t",$timestamp);

$thismonth = getdate ($timestamp);
$firstday  = $thismonth['wday'];
?>
<?php 
for ($i=0; $i<($lastdate + $firstday); $i++) 
{

	if(($i &#37; 7) == 0 ) echo "<tr>\
";

	
	if($i < $firstday) echo "<td></td>\
";

	
	else echo "<td align='center' valign='middle' height='20px'>". ($i - $firstday + 1) . "</td>\
";

	if(($i % 7) == 6 ) echo "</tr>\
";

}
?>

I tried to change the code into this,

<?php 
for ($i=0; $i<($lastdate + $firstday); $i++) 
{

	if(($i % 7) == 1 ) echo "<tr>\
";

	# if $i less than the first day (1), don't print the value of $i
	if($i < $firstday) echo "<td></td>\
";

	# print the value of $i
	else echo "<td align='center' valign='middle' height='20px'>". ($i - $firstday + 1) . "</td>\
";

	if(($i % 7) == 0 ) echo "</tr>\
";

}
?>

it then does not display properly in the column when the first day starts from Sunday…

for instance,

http://ec-ener.eu/dump/index.php?month=8&year=2010

How can I fix it? or in other words - how can I change the original script so that I can move the Sunday to the end of columns?

thanks!
Lau

p.s. I also just found out that the original code seems to have a bit problem/ bug, if you check the html - tr and td - it generates,

<tr>
<td align='center' valign='middle' height='20px'>30</td>
<td align='center' valign='middle' height='20px'>31</td>

				 
				              </table>
            </td>
        </tr>

it has the closing table in the <tr></tr> and there is only a closing </td> but no opening. strange! can I fix it?? thanks!