Setting image margins and location based on orientation This code is for Android but I guess anyone can take a chance at it.

It does what I want it to do. Just that I am not comfortable with its deep level of nesting and too much of value swapping.

Can this be optimized for readability or in compactness?

for(int imagenum, imagenum &lt;76, imagenum++){

    if (orientation.contentEquals("landscape")
            || orientation.contentEquals("reverse landscape")) {
        params.height = imageheight;
        params.width = imagewidth;
        imageButton.setImageResource(R.drawable.imageback);
        if (imagenum &lt;= 38) {

            params.leftMargin = imagenum * xspaceforeachimage;
            params.topMargin = 0;
        } else {
            params.leftMargin = (imagenum - 39) * xspaceforeachimage;
            params.topMargin = topMargin;
        }
    } else if (orientation.contentEquals("portrait")
            || orientation.contentEquals("reverse portrait")) {
        params.height = imagewidth;
        params.width = imageheight;
        imageButton.setImageResource(R.drawable.imagebacklaid);
        if (imagenum &lt;= 38) {
            params.leftMargin = 0;
            params.topMargin = imagenum * xspaceforeachimage;
        } else {
            params.leftMargin = topMargin;
            params.topMargin = (imagenum - 39) * xspaceforeachimage;
        }
    }
}
This doesn't save many lines of code, but I think it's more readable and maintainable:

boolean landscape = orientation.contains("landscape");

for(int imagenum = 0; imagenum &lt;76; imagenum++){

    /* Missing code that assigns params and imageButton using imageNum? */

    int shortSideMargin = imagenum * xspaceforeachimage;
    int longSideMargin = 0;
    if (imagenum &gt;= 39)  { //new row or column, shift back and over
        shortSideMargin -= 39 * xspaceforeachimage;
        longSideMargin = topMargin;
    }

    if (landscape) {
        params.height = imageheight;
        params.width = imagewidth;
        params.leftMargin = shortSideMargin;
        params.topMargin = longSideMargin;
        imageButton.setImageResource(R.drawable.imageback);
    } else {
        params.height = imagewidth;
        params.width = imageheight;
        params.leftMargin = longSideMargin;
        params.topMargin = shortSideMargin;
        imageButton.setImageResource(R.drawable.imagebacklaid);
    }
}