Have you tested row usage?
I haven't, but from what it looks like, it will not add another row. I'd recommend replacing that with something like...
PHP Code:
temp.w = -1;
temp.h = 0;
// Code here
if ( temp.w == replace this with ONE LESS than the number you want in each row ) {
temp.w = 0;
temp.h ++;
} else {
temp.w ++;
}
// More code here
Correct me if I'm wrong, but I'm pretty sure that would work a bit better :P