/*

This is an ugly hack to swap histogram memory data on ZEBRA. 
Ported over from sinqhttp.c. Fixing this properly would mean changes 
to the HM code. Which in turn would affect AMOR and BOA too. I also 
do not seem to need magic swaps at AMOR or BOA.....

copyright: see file COPYRIGHT

Mark Koennecke, December 2016

 */

#include <sics.h>
#include <histmem.h>
#include <sicshipadaba.h>

/*---------------------------------------------------------------*/
static void swapTrics(HistInt *data, int xdim, int ydim)
{
  int x,y, length;
	HistInt *tmpData = NULL, val;

	length = xdim*ydim;
	tmpData = malloc(length*sizeof(HistInt));
	if(tmpData == NULL){
		return;
	}
	memcpy(tmpData, data, length*sizeof(HistInt));
	for(y = 0; y < ydim; y++){
		for(x = 0; x < xdim; x++){
			val = tmpData[x*ydim + y];
			data[y*xdim+x] = val;
		}
	}
	free(tmpData);
}
/*----------------------------------------------------------------*/
int ZebraSwap(SConnection * pCon, SicsInterp * pSics, void *pData, 
             int argc, char *argv[])
{
  int xdim, ydim, status;
  pHdb dataNode = NULL;
  hdbValue val;
  
  if(argc < 4) {
    SCWrite(pCon,"ERROR: insufficient number of argument to zebraswap\nUsage: zebraswap hmdatanode xdim ydim", eError);
    return 0;
  }

  dataNode = FindHdbIntern(argv[1]);
  if(dataNode == NULL){
    SCPrintf(pCon,eError,"ERROR: data node %s not found", argv[1]);
    return 0;
  }

  status = Tcl_GetInt(InterpGetTcl(pSics),argv[2],&xdim);
  if(status != TCL_OK){
    SCPrintf(pCon,eError,"ERROR: failed to convert %s to integer", argv[2]);
    return 0;
  }

  status = Tcl_GetInt(InterpGetTcl(pSics),argv[3],&ydim);
  if(status != TCL_OK){
    SCPrintf(pCon,eError,"ERROR: failed to convert %s to integer", argv[3]);
    return 0;
  }

  val = dataNode->value;
  if(val.dataType != HIPINTVARAR || val.arrayLength < xdim*ydim){
    SCWrite(pCon,"ERROR: data type or dimension mismatch between node and parameters", eError);
    return 0;
  }
 
  swapTrics((HistInt *)val.v.intArray,xdim,ydim);
  
  SCSendOK(pCon);
  return 1;
}
