function eventHandler(win,x,y,ibut)
	global("inf", "pulseIndex", "pulse", "frame", "infIndecies", "ke9Times", "hrtsTimes", "daTime", "da", "zoomList", "statusStr", "statusCol", "daChannel");

	if ibut==-1000; return; end;
	[x,y] = xchange(x,y,'i2f')

	select ibut;
		case 0; //Left pressed, set zoom start
			zoomList = [zoomList; x, %nan];
		case -5; // Left released, set zoom end
			zoomList($,2) = x;
			doZoom();
		case 5; //Right clicked - zoom out
			if size(zoomList, 1) > 1;
				zoomList = zoomList(1:($-1), :);
				doZoom();
			end;
		case 10; //Left double-clicked - set nearby ELM
			setNearElm(x);
		case 12; //Right double-clicked - set DA threshold
			setElmThreshold(y)
		case 65362; //Up - next pulse
			moveToPulse(pulseIndex - 1);
		case 65364; //Down - next pulse
			moveToPulse(pulseIndex + 1);
		case 65361; //Left - next pulse
			moveToFrame(frame - 1);
		case 65363; //Right - next pulse
			moveToFrame(frame + 1);
		case 48 // 0) Frame Unknown
			setFrameStatus(0);
		case 49 // 1) Frame Rejected
			setFrameStatus(1);
		case 50 // 2) Frame L-Mode
			setFrameStatus(2);
		case 51 // 3) Frame Type-3 Elmy
			setFrameStatus(3);
		case 52 // 4) Frame overlapping
			setFrameStatus(4);
		case 53 // 5) Frame Good
			setFrameStatus(5);
		case 54 // 6) All Frames Reject
			setPulseStatus(1);
		case 55 // 7) All Frames L-Mode
			setPulseStatus(2);
		case 56 // 8) All Frames Type-3 Elmy
			setPulseStatus(3);
		case 44	// , 
			daChannel = daChannel - 1;
			if daChannel < 4; daChannel = 6; end;
			setInfo("Switched to ppf/s3ad/ad3"+string(daChannel));
		case 46 // .
			daChannel = daChannel + 1;
			if daChannel > 6; daChannel = 4; end;
			setInfo("Switched to ppf/s3ad/ad3"+string(daChannel));
		case 119; // 'w' Write inf
			printf("Writing to ''inf-with-elm-info.bin''\n");
			binWrite("inf-with-elm-info.bin", inf);
			printf("Total points with each status:\n");
			for i=0:5; printf("%i: %s: %i\n", i, statusStr(i+1), length(find(inf(:, 28)==i))); end;
			printf("\n");


		case -1; //mouse move, ignore
		else //anything else
			printf("%i ", ibut);

	end;

endfunction

// Sets the zoom to the current end of the zoom list
function doZoom()
	drawlater;
	f=gcf();
	ax2 = f.children(1);
	i = daTime >= zoomList($,1) & daTime < zoomList($,2);
	if length(find(i)) <= 0;
		minDA = 0; maxDA = 1;
	else
		minDA = min(da(i)); maxDA = max(da(i));
	end;
	ax2.data_bounds = [zoomList($, 1), minDA; zoomList($,2), maxDA];
	drawnow;
endfunction


function setFrameStatus0(a, b); setFrameStatus(0); endfunction;
function setFrameStatus1(a, b); setFrameStatus(1); endfunction;
function setFrameStatus2(a, b); setFrameStatus(2); endfunction;
function setFrameStatus3(a, b); setFrameStatus(3); endfunction;
function setFrameStatus4(a, b); setFrameStatus(4); endfunction;
function setFrameStatus5(a, b); setFrameStatus(5); endfunction;
function setPulseStatus1(a, b); setPulseStatus(1); endfunction;
function setPulseStatus2(a, b); setPulseStatus(2); endfunction;

function setFrameStatus(status)
	global("inf", "frame", "infIndecies");
	ii = infIndecies(frame);
	inf(ii, 28) = status
	if status < 4;
		inf(ii, 29:31) = 0; //no threshold or ELM markers for bad frame
	end;
	plotGraphMarkers();
endfunction

function setPulseStatus(status)
	global("inf", "frame", "infIndecies", "ke9Times");
	inf(infIndecies, 28) = status;
	if status < 4;
		inf(infIndecies, 29:31) = 0; //no threshold or ELM markers for bad frames
	end;
	plotGraphMarkers();
endfunction

function setElmThreshold(y)
	global("inf", "pulseIndex", "pulse", "frame", "infIndecies", "ke9Times", "hrtsTimes", "daTime", "da", "zoomList", "statusStr", "statusCol");

	if y <= 0; return; end;
	ii = infIndecies(frame);
	//inf(ii, 31) = exp(y);
	inf(ii, 31) = y;

	setElmsFromThreshold(%t); //set ELMs for this frame according to this

	plotGraphMarkers();
endfunction;

function setNearElm(t)
	global("inf", "pulseIndex", "pulse", "frame", "infIndecies", "ke9Times", "hrtsTimes", "daTime", "da", "zoomList", "statusStr", "statusCol");
	ii = infIndecies(frame);

	if t < 40 & t > 100; return; end;

	if t < ke9Times(frame);
		inf(ii, 29) = t;
	else
		inf(ii, 30) = t;
	end;

	plotGraphMarkers();
endfunction

function setElmsFromThreshold(overwriteExsiting)
	global("inf", "pulseIndex", "pulse", "frame", "infIndecies", "ke9Times", "hrtsTimes", "daTime", "da", "zoomList", "statusStr", "statusCol");

	ii = infIndecies(frame);
	threshold = inf(ii, 31);

	if overwriteExsiting | inf(ii, 29) <= 0;
		//find the last above threshold before the time point
		i = find(da > threshold & daTime < ke9Times(frame));
		if length(i) > 0;
			tElmEnd = daTime(i($));

			//find the first above threshold, before that point
			i = find(daTime < tElmEnd & da < threshold);
			if length(i) > 0;
				inf(ii, 29) = daTime(i($));
			else
				inf(ii, 29) = tElmEnd;
			end;
		end;
	end;

	if overwriteExsiting | inf(ii, 30) <= 0;
		//find the first above threshold after the time point
		i = find(da > threshold & daTime > ke9Times(frame));
		if length(i) > 0;
			inf(ii, 30) = daTime(i(1));
		end;
	end;
	
endfunction

function setInfo(str)
	global("inf", "pulseIndex", "pulse", "frame", "infIndecies", "ke9Times", "hrtsTimes", "daTime", "da", "zoomList", "statusStr", "statusCol");
	
	if frame > 0;
		status = statusStr(inf(infIndecies(frame), 28)+1);
	else 
		status = "?";
	end;
	xinfo(msprintf("Pulse %i (%i/%i), Frame %i: %s (%s)\n", pulse, pulseIndex, size(pulseList, 1), frame, status, str));
endfunction

function moveToPulse(newPulseIndex)
	global("inf", "pulseIndex", "pulse", "frame", "infIndecies", "ke9Times", "hrtsTimes", "daTime", "da", "zoomList", "statusStr", "statusCol", "daChannel");

	if newPulseIndex <= 0; newPulseIndex = size(pulseList, 1); end;
	if newPulseIndex > size(pulseList, 1); newPulseIndex = 1; end;

	pulseIndex = newPulseIndex;
	pulse = pulseList(pulseIndex);
	frame = -1;
	infIndecies = find(inf(:,1) == pulse);

	ke9Times = inf(infIndecies, 2);
	hrtsTimes = inf(infIndecies, 15);

	[da daTime x] = getSig("jet", pulse, "ppf/s3ad/ad3" + string(daChannel));

	if size(da,1) <= 0; status = 0; setInfo("No D-Alpha Data"); return; end;

	drawlater;
	clf;
	subplot(2,1,1);
	i = da > 0;
	plot(daTime(i), log(da(i)));

	ax.data_bounds(:,1) = [min(ke9Times) - 1; max(ke9Times + 1)];
	setInfo("Pulse loaded");

	moveToFrame(1);

endfunction

function moveToFrame(newFrameIndex)
	global("inf", "pulseIndex", "pulse", "frame", "infIndecies", "ke9Times", "hrtsTimes", "daTime", "da", "zoomList", "statusStr", "statusCol", "viewWindow");
	drawlater;

	if newFrameIndex <= 0; newFrameIndex = size(ke9Times, 1); end;
	if newFrameIndex > size(ke9Times, 1); newFrameIndex = 1; end;

	frame = newFrameIndex;

	//if there is already a bottom plot, delete it
	f=gcf();
	if size(f.children, 1) > 1;
		delete(f.children(1));
	end;

	subplot(2,1,2);
	ax2=gca();
	plot(daTime, da);

	ii = infIndecies(frame);

	//if this frame doesn't have an elm threshold and another does, use that


	if inf(ii, 28) == 0 | inf(ii, 28) > 3; //for undecided or good shots...
		//if this frame has a threshold, try to auto-set the ELM markers
		if inf(ii, 31) > 0;
			setElmsFromThreshold(%f); //but don't overwrite any user-set ones
		else
			//otherwise, try to find a threshold from other frames on this pulse
			i = find(inf(infIndecies, 31) > 0);
			if length(i) > 0;
				inf(ii, 31) = mean(inf(infIndecies(i), 31));
				setElmsFromThreshold(%f); //but don't overwrite any user-set ones
			end;
		end;
	end;

	setInfo("Frame loaded");
	zoomList = [min(daTime), max(daTime); ke9Times(frame) - viewWindow/2, ke9Times(frame) + viewWindow/2];

	plotGraphMarkers(frame);

endfunction

function plotGraphMarkers()
	drawlater;

	ii = infIndecies(frame);

	subplot(2,1,1);
	ax = gca();
	//remove all existing markers from plot (everything else dAlpha - the first)
	if size(ax.children, 1) > 1; delete(ax.children(1:($-1))); end;

	for f=1:size(ke9Times, 1);
		plot([ke9Times(f), ke9Times(f)], [min(log(da(da>0))), max(log(da(da>0)))], ":");
		ax.children(1).children(1).foreground = statusCol(inf(infIndecies(f), 28)+1);
		ax.children(1).children(1).thickness = 3;
	end;
	if inf(ii, 31) > 0; plot([min(daTime), max(daTime)], [log(inf(ii, 31)), log(inf(ii, 31))], ":k"); end;
	//if inf(ii, 31) > 0; plot([min(daTime), max(daTime)], [inf(ii, 31), inf(ii, 31)], ":k"); end;

	subplot(2,1,2);
	//remove all existing markers from both plots (everything else dAlpha - the first)
	ax = gca();
	if size(ax.children, 1) > 1; delete(ax.children(1:($-1))); end;

	plot([ke9Times(frame), ke9Times(frame)], [min(da), max(da)], ":");
	ax.children(1).children(1).foreground = statusCol(inf(ii, 28)+1);

	//hrts time

	plot([hrtsTimes(frame), hrtsTimes(frame)], [min(da), max(da)], "--");
	ax.children(1).children(1).foreground = color("orange");
	ax.children(1).children(1).mark_foreground = color("orange");

	//if there are ELM times
	if inf(ii, 29) > 0;
		plot([inf(ii, 29), inf(ii, 29)], [min(da), max(da)], "k");
		ax.children(1).children(1).thickness = 2;
	end;
	if inf(ii, 30) > 0;
		plot([inf(ii, 30), inf(ii, 30)], [min(da), max(da)], "k");
		ax.children(1).children(1).thickness = 2;
	end;
//	if inf(ii, 31) > 0; plot([min(daTime), max(daTime)], [log(inf(ii, 31)), log(inf(ii, 31))], ":k"); end;
	if inf(ii, 31) > 0; plot([min(daTime), max(daTime)], [inf(ii, 31), inf(ii, 31)], ":k"); end;

	doZoom();
endfunction



scf(0);
drawnow;
clf;

addmenu(0, "0) Frame Unknown", list(2,"setFrameStatus0"))
addmenu(0, "1) Frame Rejected", list(2,"setFrameStatus1"))
addmenu(0, "2) Frame L-Mode", list(2,"setFrameStatus2"))
addmenu(0, "3) Frame Type-3 Elmy", list(2,"setFrameStatus3"))
addmenu(0, "4) Frame overlapping", list(2,"setFrameStatus4"))
addmenu(0, "5) Frame Good", list(2,"setFrameStatus5"))
addmenu(0, "6) All Frames Reject", list(2,"setPulseStatus1"));
addmenu(0, "7) All Frames L-Mode", list(2,"setPulseStatus2"));

seteventhandler('eventHandler')

global("inf", "pulseIndex", "pulse", "frame", "infIndecies", "ke9Times", "hrtsTimes", "daTime", "da", "zoomList", "statusStr", "statusCol", "viewWindow");

statusStr = ["0:Unknown", "1:Rejected", "2:L-Mode", "3:Type III / High-freq", "4:Type I but HRTS not matching", "5:Good" ];
statusCol = [color("black"), color("red"), color("cyan"), color("magenta"), color(128,192,128), color("green") ];

if isdef("existingInf") & existingInf;
	printf("Using existing inf\n");
elseif length(fileinfo("inf-with-elm-info.bin")) > 0;
	inf = binRead("inf-with-elm-info.bin");
	printf("Loaded ''inf-with-elm-info.bin''\n");
else
	inf=binRead("inf-with-hrts-to-2188.bin");
	printf("Loaded ''inf-with-hrts-to-2188.bin''\n");
end;
//Relevant things:
// 1	0	80000	pulse
// 2 	40	80	ke9 Time
// 15	40	2	hrts Time
// Things we set:
// 28	0	6	ELM status (0:Unknown, 1:Rejected, 2:L-Mode, 3:Type III / High-freq, 4:Type I but HRTS-KE9 overlaps ELM, 5:Good)
// 29	40	80	Preceeding ELM Time
// 30	40	80	Next ELM Time
// 31	0	1e20	dAlpha ELM Threshold (ad36)
// 32	0	1	?
// 33	0	1	?


if size(inf, 2) < 33;
	inf = [inf, zeros(size(inf,1), 33 - size(inf,2)) ];
end;


elmInf = zeros(size(inf,1), 10);

//get pulse list from inf
i = 1;
pulseList = [];
while i <= size(inf, 1);
	pulse = inf(i, 1);
	while i <= size(inf,1) & inf(i, 1) == pulse;
		i = i + 1;
	end;
	pulseList = [pulseList; pulse];
end;

//globals
viewWindow = 0.25;
pulseIndex = -1;
pulse = -1;
frame = -1;
infIndecies = [];
daChannel = 6;

ke9Times = [];
hrtsTimes = [];

daTime = [];
da = [];

zoomList = [];

//find first pulse with a frame with unknown status
i = find(inf(:, 28) <= 0);
if length(i) <= 0; i=1; end;
pulse = inf(i(1), 1);
pi = find(pulseList == pulse);
printf("Moving to pulse %i (%i/%i) - the first with an unknown status frame\n", pulse, pi, size(pulseList, 1));
moveToPulse(pi);

