//* TODO: write correct header *//

function [fig_hdl] = ccview(rgb)
	nb_input = argn(2);

    if ndims(rgb) == 2 // gray-level image: the matrix is replicated on the 3 RGB channels
        rgb = repmat(rgb,[1,1,3]);
    end

	[ny,nx,nc] = size(rgb);



	// detect data type
	select typeof(rgb(1))
		case 'uint8'
			Max = 2 ^ 8 - 1;
			colorMap = double(matrix(rgb,nx*ny,nc)) / Max;
		case 'uint16'
			Max = 2 ^ 16 - 1;
			colorMap = double(matrix(rgb,nx*ny,nc)) / Max;
		case 'uint32'
			Max = 2 ^ 32 - 1;
    			colorMap = double(matrix(rgb,nx*ny,nc)) / Max;
		else //double?? TODO: conversion?? 
			disp("WARNING, input has been converted into integer (uint8 precision) "); 
			Max = 2 ^ 8 - 1;
			rgb = uint8(rgb);
    			colorMap = double(matrix(rgb,nx*ny,nc)) / Max; 
	end

	id = matrix(1:nx*ny,ny,nx);

	// Now let's build the image viewer
	fig_hdl = figure(); // NB: fig_hdl = figure("axes_size",[width,height],"auto_resize","off"); does not work well, because after "File", "Tools", "Edit" & "?" menus deletion, the dimensions will be wrong!
	delmenu(fig_hdl.figure_id,gettext("&File"));  //delete File menu (work for all languages)
	delmenu(fig_hdl.figure_id,gettext("&Tools")); //delete Tools menu.    
	delmenu(fig_hdl.figure_id,gettext("&Edit"));  //delete Edit menu.
	delmenu(fig_hdl.figure_id,gettext("&?"));     //delete help menu.
	format(10,1); //Indispensable, if format type is 'e' global variable names won't be correct!! 
	str_id = string(fig_hdl.figure_id);
	fig_hdl.color_map = colorMap;
	fig_hdl.figure_name = "ccview n°"+str_id;
	toolbar(fig_hdl.figure_id,'off'); //remove the toolbar.
	fig_hdl.axes_size = [nx,ny]; 
	fig_hdl.auto_resize = "off";

	fig_hdl.user_data=[0,1,Max,1,1,nx,ny]; // = [left_click_info, zoom, Max_gray_value, X1, Y1, X2, Y2] 
	//(left_click_info = 0 for "par-time left-click, 1 for "odd-time left-click" )
	// zoom_info =1 for 100%, 2 for 200% etc. 
	// X1 Y1 X2 Y2: location of the displayed subimage

	ax_hdl=gca();//get current axes handle
	ax_hdl.data_bounds = [1,1;nx,ny];
	ax_hdl.axes_visible = ["off","off","off"];
	ax_hdl.isoview = "on";
	ax_hdl.tight_limits = "on"; //axes will adapt in order to fit exactly with the data_bounds
	ax_hdl.margins = [0,0,0,0];

	// Let's declare some global variables: a copy of the inital 2 images' data, and a "to_display" variable that will be used in case of flip_mode==1
	execstr("global f" + str_id + "_initrgb");
	execstr("f" + str_id + "_initrgb = rgb"); 
	execstr("global f" + str_id + "_rgb");
	execstr("f" + str_id + "_rgb = rgb"); 

	// Now we can plot the image
	Matplot(id);
	mtplt_hdl = gce();
	mtplt_hdl.user_data=["Matplot",str_id]; //Tag the Matplot entity

	// Add an event handler function
	fig_hdl.event_handler = "event_ccview"
	fig_hdl.event_handler_enable = "on";	
endfunction


function event_ccview(win,x,y,ibut)
	scf(win);
	fig_hdl = gcf();
	str_id = string(fig_hdl.figure_id);

	if ibut == -1000 then //Quit event
		execstr("clearglobal f" + str_id + "_rgb");
		execstr("clearglobal f" + str_id + "_initrgb");
		return 
	else
		// NB: fig_hdl.user_data =  [left_click_info, zoom, Max_gray_value, X1, Y1, X2, Y2] 
		mtplt_hdl = findobj("user_data",["Matplot",str_id]); //retreive Matplot object using its tag
		execstr("global f" + str_id + "_rgb");
		execstr("global f" + str_id + "_initrgb");
		execstr("[ny,nx,nc] = size(f"+str_id+"_rgb)");

		if ibut == 3 then //left click detected
			if fig_hdl.user_data(1) then //odd-time left-click, info_message has to be killed
				fig_hdl.user_data(1)=0; 
				fig_hdl.info_message = ""; 
			else //par-time left-click, info_message has to be shown
				fig_hdl.user_data(1)=1; 
				pixval = fig_hdl.user_data(3) * fig_hdl.color_map(mtplt_hdl.data(y+1,x+1),:);
				fig_hdl.info_message = " (x="+string(x)+ " , y="+string(y) + ") value= ["+string(pixval(1))+","+string(pixval(2))+","+string(pixval(3))+"]";
			end
		end

		if ((ibut == -1)&(fig_hdl.user_data(1))) then // mouse pointer has moved AND info_message is not empty
			pixval = fig_hdl.user_data(3) * fig_hdl.color_map(mtplt_hdl.data(y+1,x+1),:);
			fig_hdl.info_message = " (x="+string(x)+ " , y="+string(y) + ") value= ["+string(pixval(1))+","+string(pixval(2))+","+string(pixval(3))+"]";
		end

		if ibut == 5 then // right-click has be done
			//update zoom factor (multiply by 2)
			fig_hdl.user_data(2) = 2 * fig_hdl.user_data(2);

			// compute location of the future subimage (X1,Y1): top left corner, (X2,Y2): top right corner
			X1 = fig_hdl.userdata(4); Y1 = fig_hdl.userdata(5);
			X2 = fig_hdl.userdata(6); Y2 = fig_hdl.userdata(7);

			ncc = 0.5*x*(X2-X1)/nx;
      			nd = .5*(X2-X1);
      			X1 = X1 + ncc; X2 = X1+nd;
      			ncc = .5*y*(Y2-Y1)/ny;
      			nd = .5*(Y2-Y1);
      			Y1 = Y1 + ncc; Y2 = Y1+nd;

			fig_hdl.userdata(4) = X1; fig_hdl.userdata(5) = Y1;
			fig_hdl.userdata(6) = X2; fig_hdl.userdata(7) = Y2;

			// perform zoom on each channel
			execstr("f"+str_id+"_rgb(:,:,1) = imresample(f"+str_id+"_initrgb(:,:,1),X1:1/fig_hdl.user_data(2):X2,Y1:1/fig_hdl.user_data(2):Y2,0)");
			execstr("f"+str_id+"_rgb(:,:,2) = imresample(f"+str_id+"_initrgb(:,:,2),X1:1/fig_hdl.user_data(2):X2,Y1:1/fig_hdl.user_data(2):Y2,0)");
			execstr("f"+str_id+"_rgb(:,:,3) = imresample(f"+str_id+"_initrgb(:,:,3),X1:1/fig_hdl.user_data(2):X2,Y1:1/fig_hdl.user_data(2):Y2,0)");

			// compute new colorMap
			execstr("fig_hdl.color_map = double(matrix(f"+str_id+"_rgb,nx*ny,nc)) / fig_hdl.user_data(3)");

			// update figure_name
			fig_hdl.figure_name = "ccview n°"+str_id+" zoom x"+string(fig_hdl.user_data(2));
		end

		if ((ibut == 4)|(ibut == 111)) then // middle click has been done or key 'o' has been pressed
			// set rgb = initrgb & update color_map
			execstr("f"+str_id+"_rgb = f"+str_id+"_initrgb");
			execstr("fig_hdl.color_map = double(matrix(f"+str_id+"_rgb,nx*ny,nc)) / fig_hdl.user_data(3)");
			fig_hdl.user_data(2) = 1;  // zoom factor
			fig_hdl.user_data(4) = 1;  // X1
			fig_hdl.user_data(5) = 1;  // Y1
			fig_hdl.user_data(6) = nx; // X2
			fig_hdl.user_data(7) = ny; // Y2
			// update figure_name
			fig_hdl.figure_name = "ccview n°"+str_id;
		end

		if ibut == 113 then //key 'q' has been pressed
			execstr("clearglobal f" + str_id + "_rgb");
			execstr("clearglobal f" + str_id + "_initrgb");
			close (fig_hdl);
		end
	end
endfunction
