/**
 * A special module for doing SANSLI rebinning. This is a fudge to make 
 * the data from the new detector electronics look like the old one.
 * 
 * copyright: see file COPYRIGHT
 *
 * Mark Koennecke, May 2007
 */
 <%! source ../sicstemplates.tcl %> 
<% stdIncludes %>
#include <math.h>
#include <sicsdata.h>
#include "rebin.h"
/*---------------------------------------------------------------------------*/
<% makeSicsFunc SansliRebin%>{
    pSICSData target = NULL, hmData = NULL;
    pNXDS dataset = NULL;
    int iDim[2], ix, iy, pos, ival;
    double x, y, val;
 
    <% testNoPar 2 4 %>    
    
    hmData = (pSICSData)FindCommandData(pSics,argv[1],"SICSData");
    if(hmData == NULL){
        SCWrite(pCon,"ERROR: histogram memory data not found",eError);
        return 0;
    }
    target = (pSICSData)FindCommandData(pSics,argv[2],"SICSData");
    if(target == NULL){
        SCWrite(pCon,"ERROR: target sicsdata not found",eError);
        return 0;
    }
    iDim[0] = 128;
    iDim[1] = 128;
    dataset = createNXDataset(2,NX_FLOAT64, iDim);
    if(dataset == NULL){
        SCWrite(pCon,"ERROR: out of memory allocating temporary data",eError);
        return 0;
    }
    
    
    for(ix = 113; ix < 415; ix++){
        for(iy = 153; iy < 363; iy++){
            x = ((double)ix - 113.)/2.359;
            y = ((double)iy - 153.)/1.640;
            getSICSDataInt(hmData,512*iy + ix,&ival);
            val = (double)ival;
            rebinPoint2D(dataset,x,y,val,TRILINEAR);
        } 
    }
    
    pos = 0;
    clearSICSData(target);
    if(argc > 3) {
        setSICSDataInt(target,0,128);
        setSICSDataInt(target,1,128);
        pos = 2;
    }
    for(ix = 0; ix < 128*128; ix++, pos++){
        setSICSDataInt(target,pos,(int)floor(dataset->u.dPtr[ix] +.5));
    }
    dropNXDataset(dataset);
    SCSendOK(pCon);
    return 1;
}
/*---------------------------------------------------------------------------*/
<% makeSicsFunc MakeSansliRebin%>{
    AddCommand(pSics,"sanslirebin", SansliRebin,NULL,NULL);
    SCSendOK(pCon);
    return 1;
}
