#include "stdio.h"
#include "string.h"
#include "C:\Program Files\Scilab-2.7\routines\stack-c.h"

int imresize __PARAMS((double *sci_data,int flag,double scale,int width,int height,double *data));

int xmu_imresize(char *fname)
{
	char	**Str;
	int		*dims,lm1, ln1, lm2, 
			 ln2,ll2, lt3, lm3, ln3,  
			 ll3,lc3;
	double	times;
	int um1=1,un1=3;
	int mL=3,nL=1,lL, un=1;
	int     it=0, dimsize=3, size;    
	double *R,*I=NULL;
	int		m1, n1, l1, m2, n2, l2, 
			m3, n3, l3, ret;

	CheckRhs(2,2);
	CheckLhs(0,1);

	GetRhsVar(2, "d", &m2, &n2, &l2);

	times=*stk(l2);

	if(VarType(1) == 1) {					// binary image
		GetRhsVar(1, "d", &m1, &n1, &l1);
		if(m1*n1 == 0) {
			Scistring("argument 1 is not a M x N usualmatrix!\n");
			return 0;
		}	
		m3=(int)(m1*times);
		n3=(int)(n1*times);
		CreateVar(3, "d", &m3, &n3, &l3);
		ret=imresize(stk(l1), 0, *stk(l2), n1, m1, stk(l3));
		if(ret == 0) {
			printf("image resize false!\n");
			return 0;
		}
		LhsVar(1) = 3;
	}

	else if(VarType(1) == 17) {				// true colormap
		GetListRhsVar(1,1,"S",&lm1,&ln1,&Str);
		if ( strcmp(Str[0],"hm") != 0) {
			Scistring("Argument 1 is not an hypermatrix!\n");
			return 0;
		}
		GetListRhsVar(1,2,"i",&lm2,&ln2,&ll2);
		GetListRhsCVar(1,3,"d",&lt3,&lm3,&ln3,&ll3,&lc3);
		dims=istk(ll2);
		if (lm2*ln2 != 3) {
		Scistring("argument 1 is not a 3D hypermatrix!\n");
		return 0;
		}
		else if (dims[2] != 3) {
			Scistring("argument 1 is not a M x N x 3 hypermatrix!\n");
			return 0;
		}
		FreeRhsSVar(Str);
		
		m3=(int)(times*times*dims[0]*dims[1]*3);
		n3=1;
		CreateVar(3, "d", &m3, &n3, &l3);

		ret=imresize(stk(ll3), 1, *stk(l2), dims[1], dims[0], stk(l3));
	
		if(ret == 0) {
			printf("image resize false!\n");
			return 0;
		}

		dims[0] = (int)(times*dims[0]);
		dims[1] = (int)(times*dims[1]);
		dims[2] = 3;
		size = dims[0]*dims[1]*3;
		R=stk(l3);
		CreateVar(4,"m", &mL, &nL, &lL);
		CreateListVarFromPtr(4,1,"S", &um1, &un1, Str);
		CreateListVarFromPtr(4,2,"i",&un, &dimsize, &dims);
		CreateListCVarFromPtr(4,3,"d", &it,&size,&un ,&R,&I);
		LhsVar(1) = 4;
	}
	return 1;
}

int imresize(double *sci_data,int flag,double scale,int width,int height,double *data)
{
	int newwidth;
	int newheight;
	int  i,j,k,m,n,dims;

	newwidth = (int)(scale * width);
	newheight = (int)(scale * height);

	if(flag == 1) 
		dims=3;
	else 
		dims=1;
	for(k=0;k<dims;k++)
		for(i=0;i<newwidth;i++)	
			for(j=0;j<newheight;j++)
			{			
				m = (int)(i/scale);
				n = (int)(j/scale);
				data[k*newwidth*newheight+i*newheight+j] = 
					sci_data[k*width*height+m*height+n];
			}
	
	return 1;
}
