/** @file  tst_psImage.c
 *
 *  @brief Contains the tests for psImage.[ch]
 *
 *
 *  @author Robert DeSonia, MHPCC
 *
 *  @version $Revision: 1.30 $ $Name: not supported by cvs2svn $
 *  @date $Date: 2005-01-04 02:34:58 $
 *
 *  Copyright 2004 Maui High Performance Computing Center, University of Hawaii
 */

#include <math.h>
#include <float.h>
#include <string.h>
#include <stdlib.h>

#include "psTest.h"
#include "pslib.h"
#include "psType.h"

static psS32 testImageAlloc(void);
static psS32 testImageCopy(void);
static psS32 testRegion(void);

testDescription tests[] = {
                              {testImageAlloc,546,"psImageAlloc",0,false},
                              {testImageAlloc,548,"psImageFree",0,true},
                              {testImageCopy,551,"psImageCopy",0,false},
                              {testRegion,790,"psRegionAlloc",0,false},
                              {testRegion,791,"psRegionFromString",0,true},
                              {NULL}
                          };

psS32 main(psS32 argc, char* argv[])
{
    psLogSetLevel(PS_LOG_INFO);

    return ! runTestSuite(stderr,"psImage",tests,argc,argv);
}

psS32 testImageAlloc(void)
{
    psImage* image = NULL;
    psU32 sizes = 6;
    psU32 numCols[] = {
                          0,1,1,100,100,150
                      };
    psU32 numRows[] = {
                          0,1,100,1,150,100
                      };
    psU32 types = 13;
    psElemType type[] = { PS_TYPE_S8, PS_TYPE_S16, PS_TYPE_S32, PS_TYPE_S64,
                          PS_TYPE_U8, PS_TYPE_U16, PS_TYPE_U32, PS_TYPE_U64,
                          PS_TYPE_F32, PS_TYPE_F64, PS_TYPE_C32, PS_TYPE_C64,
                          PS_TYPE_PTR };

    psLogMsg(__func__,PS_LOG_INFO,"#546 - psImageAlloc shall allocate memory for a psImage structure");

    for (psU32 t=0;t<types;t++) {
        psLogMsg(__func__,PS_LOG_INFO,"Testing psImage with type %xh",type[t]);

        for (psU32 i=0;i<sizes;i++) {

            if (numRows[i] == 0 || numCols[i] == 0) {
                psLogMsg(__func__,PS_LOG_INFO,"Following should be an error.");
            }

            image = psImageAlloc(numCols[i],numRows[i],type[t]);

            if (image == NULL) {
                if (numRows[i] == 0 || numCols[i] == 0) {
                    continue;
                }
                psError(PS_ERR_UNKNOWN, true,"psImageAlloc returned NULL for type %x, size %dx%d.",
                        type[t], numCols[i], numRows[i]);
                psFree(image);
                return 1;
            }

            if (image->type.dimen != PS_DIMEN_IMAGE || image->type.type != type[t]) {
                psError(PS_ERR_UNKNOWN, true,"psImageAlloc allocated wrong dimen/type (%d/%d), should be "
                        "PS_IMAGE_DIMEN/%d", image->type.dimen, image->type.type, type[t]);
                psFree(image);
                return 2;
            }

            if (image->numCols != numCols[i] || image->numRows != numRows[i]) {
                psError(PS_ERR_UNKNOWN, true,"psImageAlloc allocated wrong size %dx%d, should be %dx%d (type = %d)",
                        image->numCols, image->numRows, numCols[i], numRows[i],type[t]);
                psFree(image);
                return 3;
            }

            if (image->col0 != 0 || image->row0 != 0) {
                psError(PS_ERR_UNKNOWN, true,"psImageAlloc returned row0/col0 of %d/%d.  Should be 0/0.",
                        image->row0, image->row0);
                psFree(image);
                return 4;
            }

            if (image->parent != NULL) {
                psError(PS_ERR_UNKNOWN, true,"psImageAlloc returned non-NULL parent");
                psFree(image);
                return 5;
            }

            if (image->children != NULL) {
                psError(PS_ERR_UNKNOWN, true,"psImageAlloc returned non-NULL children array");
                psFree(image);
                return 7;
            }

            switch (type[t]) {
            case PS_TYPE_U16: {
                    psU32 rows = numRows[i];
                    psU32 cols = numCols[i];

                    for (psS32 r=0;r<rows;r++) {
                        for (psS32 c=0;c<cols;c++) {
                            image->data.U16[r][c] = 2*c+r;
                        }
                    }
                    for (psS32 r=0;r<rows;r++) {
                        for (psS32 c=0;c<cols;c++) {
                            if (image->data.U16[r][c] != 2*c+r) {
                                psError(PS_ERR_UNKNOWN, true,"Could not set all pixels in uint16 image at (%d,%d)",c,r);
                                psFree(image);
                                return 8;
                            }
                        }
                    }
                }
                break;
            case PS_TYPE_F32: {
                    psU32 rows = numRows[i];
                    psU32 cols = numCols[i];

                    for (psS32 r=0;r<rows;r++) {
                        for (psS32 c=0;c<cols;c++) {
                            image->data.F32[r][c] = 2.0f*c+r;
                        }
                    }
                    for (psS32 r=0;r<rows;r++) {
                        for (psS32 c=0;c<cols;c++) {
                            if (fabsf(image->data.F32[r][c] - (2.0f*c+r)) > FLT_EPSILON) {
                                psError(PS_ERR_UNKNOWN, true,"Could not set all pixels in float image at (%d,%d)",c,r);
                                psFree(image);
                                return 8;
                            }
                        }
                    }
                }
                break;
            case PS_TYPE_F64: {
                    psU32 rows = numRows[i];
                    psU32 cols = numCols[i];

                    for (psS32 r=0;r<rows;r++) {
                        for (psS32 c=0;c<cols;c++) {
                            image->data.F64[r][c] = 2.0f*c+r;
                        }
                    }
                    for (psS32 r=0;r<rows;r++) {
                        for (psS32 c=0;c<cols;c++) {
                            if (fabs(image->data.F64[r][c] - (2.0f*c+r)) > DBL_EPSILON) {
                                psError(PS_ERR_UNKNOWN, true,"Could not set all pixels in double image at (%d,%d)",c,r);
                                psFree(image);
                                return 8;
                            }
                        }
                    }
                }
                break;
            case PS_TYPE_C32: {
                    psU32 rows = numRows[i];
                    psU32 cols = numCols[i];

                    for (psS32 r=0;r<rows;r++) {
                        for (psS32 c=0;c<cols;c++) {
                            image->data.C32[r][c] = r + I * c;
                        }
                    }
                    for (psS32 r=0;r<rows;r++) {
                        for (psS32 c=0;c<cols;c++) {
                            if (fabsf(crealf(image->data.C32[r][c]) - r) > FLT_EPSILON ||
                                    fabsf(cimagf(image->data.C32[r][c]) - c) > FLT_EPSILON ) {
                                psError(PS_ERR_UNKNOWN, true,"Could not set all pixels in complex image at (%d,%d)",c,r);
                                psFree(image);
                                return 8;
                            }
                        }
                    }
                }
                break;
            case PS_TYPE_PTR: {
                    psU32 rows = numRows[i];
                    psU32 cols = numCols[i];
                    psImage* temp = psImageAlloc(1,1,PS_TYPE_F32);

                    for (psS32 r=0;r<rows;r++) {
                        for (psS32 c=0;c<cols;c++) {
                            image->data.PTR[r][c] = psMemIncrRefCounter(temp);
                        }
                    }
                    for (psS32 r=0;r<rows;r++) {
                        for (psS32 c=0;c<cols;c++) {
                            if (image->data.PTR[r][c] != temp) {
                                psError(PS_ERR_UNKNOWN, true, "Could not set pixel in pointer image at (%d,%d): %x %x",
                                        c,r,image->data.PTR[r][c],temp);
                                psFree(image);
                                psFree(temp);
                                return 8;
                            }
                        }
                    }
                    psFree(temp);
                }
                break;
            default: {
                    // ignore type and just use as byte bucket.
                    psU32 rows = numRows[i];
                    psU32 cols = numCols[i]*PSELEMTYPE_SIZEOF(type[t]);

                    for (psS32 r=0;r<rows;r++) {
                        for (psS32 c=0;c<cols;c++) {
                            image->data.U8[r][c] = (uint8_t)(r + c);
                        }
                    }
                    for (psS32 r=0;r<rows;r++) {
                        for (psS32 c=0;c<cols;c++) {
                            if (image->data.U8[r][c] != (uint8_t)(r + c)) {
                                psError(PS_ERR_UNKNOWN, true,"Could not set all pixels in image (type=%d) at (%d,%d)",
                                        type[t],c,r);
                                psFree(image);
                                return 8;
                            }
                        }
                    }
                }
            }
            psFree(image);
        }
    }

    // #548: Verify no memory leaks or corruption are detected after a valid psImage structure with multiple
    // children is freed.
    image = psImageAlloc(100,100,PS_TYPE_F32);
    psImageSubset(image,50,0,70,20);
    psImageSubset(image,70,20,90,40);

    psFree(image);

    return 0;
}

psS32 testImageCopy(void)
{
    psImage* img = NULL;
    psImage* img2 = NULL;
    psImage* img3 = NULL;
    psImage* img4 = NULL;
    psU32 c = 128;
    psU32 r = 256;

    img = psImageAlloc(c,r,PS_TYPE_F32);
    for (unsigned row=0;row<r;row++) {
        psF32* imgRow = img->data.F32[row];
        for (unsigned col=0;col<c;col++) {
            imgRow[col] = (psF32)(row+col);
        }
    }
    img2 = psImageAlloc(c,r,PS_TYPE_F32);
    for (unsigned row=0;row<r;row++) {
        psF32* img2Row = img2->data.F32[row];
        for (unsigned col=0;col<c;col++) {
            img2Row[col] = 0.0f;
        }
    }

    img3 = psImageCopy(img2,img,PS_TYPE_F32);

    // Verify the returned psImage structure pointer is equal to the input parameter output.
    if (img2 != img3) {
        psError(PS_ERR_UNKNOWN, true,"the image given for recycled wasn't");
        return 1;
    }

    // Verify the returned psImage structure is the same type as the input image structure
    // if the specified output argument is NULL.
    img4 = psImageCopy(NULL,img,PS_TYPE_F32);
    if (img4 == NULL) {
        psError(PS_ERR_UNKNOWN, true,"output image doesn't exist");
        return 4;
    }
    if (img4->type.type != img->type.type) {
        psError(PS_ERR_UNKNOWN, true,"output image is not the same type as input image");
        return 4;
    }
    for (psU32 row=0;row<r;row++) {
        psF32* imgInRow = img->data.F32[row];
        psF32* imgOutRow = img4->data.F32[row];
        for (unsigned col=0;col<c;col++) {
            if( imgInRow[col] != imgOutRow[col] ) {
                psError(PS_ERR_UNKNOWN, true,"Input image not equal to output image at %d,%d!",
                        col, row);
                return 4;
            }
        }
    }

    // Verify the returned psImage structure member are equal to the values in
    // the input psImage structure input.

    #define testImageCopyType(IN,OUT) \
    img = psImageRecycle(img,c,r,PS_TYPE_##IN); \
    for (unsigned row=0;row<r;row++) { \
        ps##IN* imgRow = img->data.IN[row]; \
        for (unsigned col=0;col<c;col++) { \
            imgRow[col] = (ps##IN)(row+col); \
        } \
    } \
    img2 = psImageCopy(img2,img,PS_TYPE_##OUT); \
    if (img2 == NULL) { \
        psError(PS_ERR_UNKNOWN, true,"psImageCopy failed to copy U8."); \
        return 2; \
    } \
    for (psU32 row=0;row<r;row++) { \
        ps##IN* imgRow = img->data.IN[row]; \
        ps##OUT* img2Row = img2->data.OUT[row]; \
        for (psU32 col=0;col<c;col++) { \
            if (abs(imgRow[col] - (ps##IN)(row+col)) > 0.5) { \
                psError(PS_ERR_UNKNOWN, true,"Input image was changed at %d,%d!", \
                        col,row); \
                return 2; \
            } \
            if (abs(img2Row[col] - (ps##OUT)(imgRow[col])) > 0.5) { \
                psError(PS_ERR_UNKNOWN, true,"returned psImage values after copy don't match at %d,%d " \
                        "(%d vs %d)",\
                        col,row,img2Row[col], (ps##OUT)(imgRow[col])); \
                return 2; \
            } \
        } \
    }

    #define testImageCopyTypes(IN) \
    printf("to psF32\n"); \
    testImageCopyType(IN,F32);\
    printf("to psF64\n"); \
    testImageCopyType(IN,F64); \
    printf("to psU8\n"); \
    testImageCopyType(IN,U8); \
    printf("to psU16\n"); \
    testImageCopyType(IN,U16); \
    printf("to psU32\n"); \
    testImageCopyType(IN,U32); \
    printf("to psS8\n"); \
    testImageCopyType(IN,S8);\
    printf("to psS16\n"); \
    testImageCopyType(IN,S16);\
    printf("to psS32\n"); \
    testImageCopyType(IN,S32);

    psLogMsg(__func__,PS_LOG_INFO,"Image Copy Test for psU8");
    testImageCopyTypes(U8);
    psLogMsg(__func__,PS_LOG_INFO,"Image Copy Test for psU16");
    testImageCopyTypes(U16);
    psLogMsg(__func__,PS_LOG_INFO,"Image Copy Test for psU32");
    testImageCopyTypes(U32);
    psLogMsg(__func__,PS_LOG_INFO,"Image Copy Test for psS8");
    testImageCopyTypes(S8);
    psLogMsg(__func__,PS_LOG_INFO,"Image Copy Test for psS16");
    testImageCopyTypes(S16);
    psLogMsg(__func__,PS_LOG_INFO,"Image Copy Test for psS32");
    testImageCopyTypes(S32);
    psLogMsg(__func__,PS_LOG_INFO,"Image Copy Test for psF32");
    testImageCopyTypes(F32);
    psLogMsg(__func__,PS_LOG_INFO,"Image Copy Test for psF64");
    testImageCopyTypes(F64);

    // Verify the returned psImage structure pointer is null and program
    // execution doesn't stop, if the input parameter input is null.
    psLogMsg(__func__,PS_LOG_INFO,"An error should follow...");
    img3 = psImageCopy(NULL,NULL,PS_TYPE_F32);
    if (img3 != NULL) {
        psError(PS_ERR_UNKNOWN, true,"psImageCopy didn't return NULL when input image was NULL.");
        return 3;
    }

    psFree(img);
    psFree(img2);
    psFree(img3);
    psFree(img4);

    return 0;
}

static psS32 testRegion(void)
{
    int testNum = 0;


    // Testpoint #790

    psRegion* region = psRegionAlloc(1,2,3,4);

    testNum++;
    if (region == NULL) {
        psError(PS_ERR_UNKNOWN, false,
                "psRegionAlloc returned a NULL pointer.");
        return testNum;
    }

    testNum++;
    if (region->x0 != 1 || region->x1 != 2 || region->y0 != 3 || region->y1 != 4) {
        psError(PS_ERR_UNKNOWN, false,
                "The region attributes are not set properly (%s)",
                psRegionToString(region));
        return testNum;
    }

    psFree(region);

    // Testpoint #791

    region = psRegionFromString("[1:2,3:4]");

    testNum++;
    if (region == NULL) {
        psError(PS_ERR_UNKNOWN, false,
                "psRegionFromString returned a NULL pointer.");
        return testNum;
    }

    testNum++;
    if (region->x0 != 1 || region->x1 != 2 || region->y0 != 3 || region->y1 != 4) {
        psError(PS_ERR_UNKNOWN, false,
                "The region attributes are not set properly (%s)",
                psRegionToString(region));
        return testNum;
    }

    psFree(region);
    region = psRegionFromString("[1:2,3:]");

    testNum++;
    if (region != NULL) {
        psError(PS_ERR_UNKNOWN, false,
                "psRegionFromString returned a non-NULL pointer given a malformed string.");
        return testNum;
    }

    return 0;
}
