Grid Allignment of Objects/Images

Hi guys im making an flash app which sorts images into various arrangements but im having trouble getting the grid arrangement to sort properly and display the images in a proper grid arrangment. Some images get sorted and aligned in the grid arrangement but others dont…

here is the code maybe someone can help me.

private function gridPhotos(e:Event):void
	{
	
		//Tweener.addTween(spr2, {scaleX: targetScale, scaleY: 5.0, rotation:180, time:1.0, transition:"easeinoutquad"});
		
		const gap:int = 15; // horizental and vertical gap
		
		var rowWidth:int = gap; // current row width
		var rowBaseline:int = gap; // baseline of current row
		var rowHeight:int = gap; // height of the tallest child in current row
		
		var n:int = photos.numChildren;
		for(var i:int = 0; i<n; i++)
		{	
			minX = -500, maxX = 2700;
			minY = -450, maxY = 2000;
			
			var child:DisplayObject = photos.getChildAt(i);
			if(child is Shape) continue; // void its 'clickgrabber'
			if(child is Wrapper) continue;
			var bounds:Rectangle = child.getBounds(photos);
			var selfBounds:Rectangle = child.getBounds(child);
			var xOff:Number = selfBounds.x * child.scaleX;
			var yOff:Number = selfBounds.y * child.scaleY;
			trace(bounds);
			
			if(bounds.height > rowHeight) rowHeight = bounds.height;
			
			var targetX:int = rowWidth-xOff+minX;
			var targetY:int = rowBaseline-yOff+minY;
			var targetRotation:int = 0;			
			//var targetRotation:int = photos.rotation;
	
			
			var targetScale:Number = 0.08;	
		
			
			rowWidth += bounds.width + gap;
			if(rowWidth > maxX) // need to start a new row
			{
				rowWidth = gap;
				rowBaseline += rowHeight + gap;
				rowHeight = gap;
				
				targetX = rowWidth-xOff;
				targetY = rowBaseline-yOff;
				
			}
		Tweener.addTween(child, {scaleX: targetScale, scaleY: targetScale, rotation:targetRotation, x:targetX, y:targetY, time:0.65, transition:"easeinoutquad"});
		//syncPhotos(child);
		}
	}

Thanks in advance