package com.android.application;

import java.io.OutputStreamWriter;
import java.util.Vector;


import com.android.Algorithm.*;
//import com.android.testbtspp2_1.*;
import com.android.main.*;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Paint.Style;
import android.graphics.drawable.GradientDrawable;
import android.opengl.Matrix;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class SkullmapPullballActivity extends Activity{
	private SkullmapPullballView pdasv;
	protected void onCreate(Bundle bb) {
		super.onCreate(bb);
		pdasv = new SkullmapPullballView(this);
		setContentView(pdasv);
	}
	@Override
    public void onStop() {
         super.onStop();
         pdasv.dfftthread.setStopTag(true);
         
         finish();
         System.gc();
    }
	class SkullmapPullballView extends View implements View.OnTouchListener, View.OnLongClickListener{
		private Buffer buffer;
		private Paint paint;
		private int sampleRate;
		private boolean DEBUG = true;
		private final int secondForFFT = 4;//Must be 4-times, i.e. 4,8,12,16...once modify here, modify in Channel.class as well.
		private String TAG = "SkullmapPullballView";
		private float oriDistanceOfFingers;
		private int selectionForNextDisplay;
		private float oriXAxis,oriYAxis;//for one finger, swipe screen
		private String msgToDisplay = "";
		private Channel [] element;
		private DrawFFTThread dfftthread;
		private int indexForDataBuffer;
		private FastFourierTransform fft;
		//frames to display FFT result
		private int signalFrameWidth, signalFrameHeight;
		private int skullMapWidth, skullMapHeight;
		private final int picChannelWidth=50,picChannelHeight= 50;
		private final int topBottomGap=50, leftSideGap=15, rightSideGap = 20, skullSignalGap=10;
		//private int ch1MaxIndex = 0,ch2MaxIndex = 0,ch3MaxIndex = 0,ch4MaxIndex = 0;//Max index after FFT.
		private final int MIN_SLIDE_DISTANCE = 200;
		private boolean filterTag;
		private Toast popMsg;
		private int [] selectedChannelTable;
		private int nextIndexSelectedChannelTable;
		private Bitmap bitmapOrg,bitmapAfter,bitmapAlphaw,bitmapAlphag,bitmapBetaw,bitmapBetag,bitmapThetaw,bitmapThetag;
		private RectF rectForBitmap, rectForBitmapAlpha,rectForBitmapBeta,rectForBitmapTheta;
		private boolean isAlphaPressed,isBetaPressed,isThetaPressed;
		private int startTimeToDraw;//used as an index that indicates which moment to draw; 0 is default.
		private int xAxisExtend;//xAxisExtend=0(default), 1-pixel displays 1pts; xAxisExtend=1, 2-pixels display 1pts
		private final int baseLineSecond;//extract the Maximum value from 0 to baseLineSecond
		private boolean baseLineSecondTag;//baseLineSecondTag=false(default), if executionTime==baseLineSecond then baseLineSecondTag=true;
		private GradientDrawable mDrawable;
		private int powerDifferenceOfTwoChannels;
		private float powerDifferenceOfTwoChannels_float;
		private Bitmap bitmapBall;
		private RectF rectForBitmapBall;
		private int ballOffset;
		//for plus(0.1),subtract(0.1),times10,divide10,plus1,subtract1 bitmap
		private Bitmap bitmapPlus, bitmapSubtract,bitmapTimes10,bitmapDivide10,bitmapPlus1,bitmapSubtract1,bitmapRatiobydivide,bitmapRatiobyplus;
		private RectF rectForBitmapPlus,rectForBitmapSubtract, rectForBitmapTimes10, rectForBitmapDivide10,rectForBitmapPlus1,rectForBitmapSubtract1,rectForBitmapRatiobydivide,rectForBitmapRatiobyplus;
		private float ratioBase;
		private String ratioTag;//PLUS or DIVIDE
		//for base line array
		private float baseline;
		private int baselineLength = 10;//initial
		private final int baselineLengthFixed = 10;
		
		public SkullmapPullballView(Context context){
			super(context);
			setTitle("SkullmapAndPullball");
			sampleRate = buffer.sRate;
			paint = new Paint();
			paint.setStyle(Paint.Style.STROKE);
			paint.setStrokeWidth(1);
			setOnTouchListener(this);
			setLongClickable(false);
			setOnLongClickListener(this);
			oriDistanceOfFingers = 0;
			selectionForNextDisplay = -1;//initial, should be set by longClick
			oriXAxis = 0;
			oriYAxis = 0;
			element = new Channel[buffer.channels];
			
			for (int i=0;i<buffer.channels;i++){
				element[i] = new Channel(Integer.toString(i));
			}
			indexForDataBuffer = 0;//0,1,2,...,secondForFFT-1
			fft = new FastFourierTransform();
			filterTag = false;
			popMsg = new Toast(getContext());
			selectedChannelTable = new int[2];//at least 1 channel; 0:first row, 1:second row, 2:third row, 3:fourth row
			skullMapWidth = 500;
			skullMapHeight = (520-topBottomGap);
			signalFrameWidth = 1024-leftSideGap-rightSideGap-skullMapWidth;
			signalFrameHeight = (520-topBottomGap*2)/selectedChannelTable.length; // 450/2
			nextIndexSelectedChannelTable = 0;
			
			initial();//initial the table and FFT channel
			
			bitmapOrg = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.eeglayout);
			bitmapAlphaw = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.alphaw);
			bitmapAlphag = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.alphag);
			bitmapBetaw = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.betaw);
			bitmapBetag = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.betag);
			bitmapThetaw = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.thetaw);
			bitmapThetag = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.thetag);
			bitmapBall = BitmapFactory.decodeResource(getResources(), R.drawable.ball);
			rectForBitmapBall = new RectF(0,0,100,100);
			//bitmapOrg = bitmapOrg.copy(bitmapOrg.getConfig(), true);
			bitmapAfter = bitmapOrg.copy(bitmapOrg.getConfig(), true);
			rectForBitmap = new RectF(leftSideGap,topBottomGap,leftSideGap+skullMapWidth,topBottomGap+skullMapHeight);
			rectForBitmapTheta = new RectF(0,0,picChannelWidth+20,picChannelHeight+20);
			rectForBitmapAlpha = new RectF(0,picChannelHeight+20,picChannelWidth+20,picChannelHeight+20+picChannelHeight+20);
			rectForBitmapBeta = new RectF(0,(picChannelHeight+20)*2,picChannelWidth+20,(picChannelHeight+20)*2+picChannelHeight+20);
			isThetaPressed = false;
			isAlphaPressed = true;
			isBetaPressed = false;
			startTimeToDraw = 0;
			xAxisExtend = 1;
			baseLineSecond = 10;
			baseLineSecondTag = false;
			mDrawable = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT ,
                     new int[] { Color.rgb(0, 0, 255) , Color.rgb(0, 255, 255),Color.rgb(0, 255, 0),Color.rgb(255, 255, 0),Color.rgb(255, 0, 0) });
			//mDrawable = new GradientDrawable(GradientDrawable.Orientation.LEFT_RIGHT ,new int[] { 0x880000FF , 0x8800FF00,0x8800FFFF,0x88FF0000,0x88FFF00 });
			mDrawable.setShape(GradientDrawable.RECTANGLE);
			mDrawable.setBounds(new Rect(0,0,200,10));
            mDrawable.setGradientRadius((float)(Math.sqrt(2) * 60));
            mDrawable.setGradientType(GradientDrawable.LINEAR_GRADIENT);
            powerDifferenceOfTwoChannels = 0;
            powerDifferenceOfTwoChannels_float = 0;
            ballOffset = 0;
            // for plus(0.1), subtract(0.1),times10,divide10 bitmap, plus1, subtract1
            bitmapPlus = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.plus);
            bitmapSubtract = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.subtract);
            bitmapTimes10 = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.times10);
            bitmapDivide10 = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.divide10);
            bitmapPlus1 = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.plus1);
            bitmapSubtract1 = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.subtract1);
            bitmapRatiobydivide = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.ratiobydivide);
            bitmapRatiobyplus = BitmapFactory.decodeResource(getResources(), 
		               R.drawable.ratiobyplus);
            rectForBitmapPlus1= new RectF(650,0,650+picChannelWidth,0+picChannelHeight);
            rectForBitmapSubtract1 = new RectF(750,0,750+picChannelWidth,0+picChannelHeight);
            rectForBitmapTimes10= new RectF(650,50,650+picChannelWidth,50+picChannelHeight);
            rectForBitmapDivide10 = new RectF(750,50,750+picChannelWidth,50+picChannelHeight);
            rectForBitmapPlus= new RectF(650,100,650+picChannelWidth,100+picChannelHeight);
            rectForBitmapSubtract = new RectF(750,100,750+picChannelWidth,100+picChannelHeight);
			rectForBitmapRatiobydivide = new RectF(650,150,650+picChannelWidth,150+picChannelHeight);
			rectForBitmapRatiobyplus = new RectF(750,150,750+picChannelWidth,150+picChannelHeight);
            ratioBase = 50.0f;
            ratioTag = "DIVIDE";
            
            baseline = 1;
            
            dfftthread = new DrawFFTThread(mHandler,"SkullmapPullballViewThread");
			dfftthread.start();
            /*try {   // open myfilename.txt for writing   
            	OutputStreamWriter out = new OutputStreamWriter(openFileOutput("/external_sd/alert.txt",0));    
            	// write the contents on mySettings to the file   
            	out.write("this is a test");   // close the file   
            	out.flush();
            	out.close(); 
            	} 
            catch (java.io.IOException e) {   //do something if an IOException occurs. 
            	Log.i(TAG, "java.io.IOException @ write to file");
            } */
		}
		private void initial2(){
			for(int i=0;i<selectedChannelTable.length;i++){
				selectedChannelTable[i]= i+1;
				element[i].isSelected = true;
			}
		}

		/*public Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {         
			Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());         
			Canvas canvas = new Canvas(bmOverlay);         
			canvas.drawBitmap(bmp1, new Matrix(), null);         
			canvas.drawBitmap(bmp2, 0, 0, null);         
			return bmOverlay;     
		}*/
		private void setData(Vector v){
			synchronized(this){
				if(DEBUG)Log.e(TAG, "In setData()");			
				if(v.size()>0){
				  //if(DEBUG)buffer.writeData(2,TAG+", in setData()"+v.size());
					putDataIntoDataBuffer(v);//put data into dataBuffer, and filter
					FFT();//FFT
					element[0].indexOfSumAlpha++;
					
					if(element[0].indexOfSumAlpha >=(element[0].FFTResultData.length)&& element[0].indexOfSumAlpha % (element[0].FFTResultData.length)==0)//reach display limit
						this.startTimeToDraw = ((int)(element[0].indexOfSumAlpha/(element[0].FFTResultData.length)))*(element[0].FFTResultData.length)-1;
					//msgToDisplay =element[0].indexOfSumAlpha+"/"+ startTimeToDraw+"/"+xAxisExtend;
					if(ratioTag.equalsIgnoreCase("PLUS"))
						modifyScale_plus();	
					else
						modifyScale_ratio();
					
					calculateBaseline();
						
					//msgToDisplay = (int)elemenft[0].sumTheta[element[0].indexOfSumAlpha-1]+"("+(int)element[0].tempThetaMax+")"+"/ "+(int)element[0].sumAlpha[element[0].indexOfSumAlpha-1]+"("+(int)element[0].tempAlphaMax+")"+"/ "+
					//(int)element[0].sumBeta[element[0].indexOfSumAlpha-1]+"("+(int)element[0].tempBetaMax+")"+"/ "+(element[0].indexOfSumAlpha-1);
					invalidate();//paint
				}
			}
			
		}
		private void calculateBaseline(){
			if(element[0].indexOfSumAlpha-1 == baselineLength){
				float temp1 = 0, temp2 = 0;;
				if(isThetaPressed){
					for(int i=baselineLength-10;i<baselineLength;i++){
						temp1 +=element[selectedChannelTable[0]-1].sumTheta[i];
						temp2 +=element[selectedChannelTable[1]-1].sumTheta[i];
					}
					temp1 /=baselineLengthFixed;
					temp2 /=baselineLengthFixed;
					if(ratioTag.equalsIgnoreCase("DIVIDE"))
						baseline = temp1/temp2;
					else
						baseline = temp1+temp2;
				}
				else if(isAlphaPressed){
					for(int i=baselineLength-10;i<baselineLength;i++){
						temp1 +=element[selectedChannelTable[0]-1].sumAlpha[i];
						temp2 +=element[selectedChannelTable[1]-1].sumAlpha[i];
					}
					temp1 /=baselineLengthFixed;
					temp2 /=baselineLengthFixed;
					if(ratioTag.equalsIgnoreCase("DIVIDE"))
						baseline = temp1/temp2;
					else
						baseline = temp1+temp2;
				}
				else if(isBetaPressed){
					for(int i=baselineLength-10;i<baselineLength;i++){
						temp1 +=element[selectedChannelTable[0]-1].sumBeta[i];
						temp2 +=element[selectedChannelTable[1]-1].sumBeta[i];
					}
					temp1 /=baselineLengthFixed;
					temp2 /=baselineLengthFixed;
					if(ratioTag.equalsIgnoreCase("DIVIDE"))
						baseline = temp1/temp2;
					else
						baseline = temp1+temp2;
				}
				ratioBase = baseline;
			}
		}
		private void putDataIntoDataBuffer(Vector v2){
			//double [][] temp;
			//if(DEBUG)Log.e(TAG, "in putDataIntoDataBuffer()");
			//if(DEBUG)Log.e(TAG, "in putDataIntoDataBuffer()/v= "+v.size());
			if(filterTag){
				for(int channel=0;channel<buffer.channels;channel++){
					element[channel].oneSecData = element[channel].filter.filter((double[])v2.elementAt(channel));
				}
			}
			else{
				for(int channel=0;channel<buffer.channels;channel++){
					//try{
					element[channel].oneSecData = (double[])v2.elementAt(channel);
					//}catch (ArrayIndexOutOfBoundsException a){ Log.e(TAG, "ArrayIndexOutOfBoundsException");}
				}
			}
			//buffer.write3array(element[0].oneSecData, element[1].oneSecData,element[2].oneSecData, element[0].indexOfSumAlpha%128);
			if(indexForDataBuffer>=secondForFFT){//no more place to fill in the data
				//move data to previous one sec.
				for(int channel=0;channel<buffer.channels;channel++){
					for (int i = 0; i < (secondForFFT-1); i++) {
	                    for (int j = 0; j < sampleRate; j++) {
	                    	element[channel].oriData[i * sampleRate +j] = element[channel].oriData[i * sampleRate + j + sampleRate];
	                    }
	                }
				}
				//insert data to last sec.
				for(int channel=0;channel<buffer.channels;channel++){
					System.arraycopy(element[channel].oneSecData, 0, element[channel].oriData, (indexForDataBuffer-1)*sampleRate, sampleRate);
				}
			}
			else{
				//insert data to last sec.
				for(int channel=0;channel<buffer.channels;channel++){
					System.arraycopy(element[channel].oneSecData, 0, element[channel].oriData, indexForDataBuffer*sampleRate, sampleRate);
				}
			}
			indexForDataBuffer++;
			if(indexForDataBuffer==(secondForFFT+1))
				indexForDataBuffer = secondForFFT;
			//msgToDisplay = Integer.toString(indexForDataBuffer);
			//if(DEBUG)Log.e(TAG, "in putDataIntoDataBuffer(), DONE");
		}
		private void FFT(){
			//if(DEBUG)Log.e(TAG, "in FFT()");
			//synchronized(this){
				for(int channel=0;channel<buffer.channels;channel++){
					//if(element[channel].isSelected){
						element[channel].FFTResultData = fft.fftMag2(element[channel].oriData);	
						//if(DEBUG)Log.d(TAG,"element["+channel+"].indexOfSumAlpha= "+element[channel].indexOfSumAlpha);
						//if(DEBUG)Log.e(TAG, "element["+channel+"].sumTheta["+element[channel].indexOfSumAlpha+"]= "+element[channel].sumTheta[element[channel].indexOfSumAlpha]);
						for(int i=(3*secondForFFT);i<(6.75*secondForFFT);i++){//theta
							
							element[channel].sumTheta[element[channel].indexOfSumAlpha] += element[channel].FFTResultData[i];
						}
						for(int i=(11*secondForFFT);i<(15*secondForFFT);i++){//alpha
							//if(channel==0)
							//if(DEBUG)Log.e(TAG, "in FFT, FFTResultData["+i+"]= "+element[channel].FFTResultData[i]);
							element[channel].sumAlpha[element[channel].indexOfSumAlpha] += element[channel].FFTResultData[i];
						}
						for(int i=(int)(12.25*secondForFFT);i<(25*secondForFFT);i++){//beta
							element[channel].sumBeta[element[channel].indexOfSumAlpha] += element[channel].FFTResultData[i];
						}
						
						//element[channel].indexOfSumAlpha++;
						//if(element[channel].indexOfSumAlpha>=120)//reach 2 min
						//	element[channel].indexOfSumAlpha = 0;
					//}
				}
				if(DEBUG)Log.i(TAG, "in FFT, sumTheta["+element[0].indexOfSumAlpha+"]= "+element[0].sumTheta[element[0].indexOfSumAlpha]);
				if(DEBUG)Log.i(TAG, "in FFT, sumAlpha["+element[0].indexOfSumAlpha+"]= "+element[0].sumAlpha[element[0].indexOfSumAlpha]);
				if(DEBUG)Log.i(TAG, "in FFT, sumBeta["+element[0].indexOfSumAlpha+"]= "+element[0].sumBeta[element[0].indexOfSumAlpha]);
				//}
			//if(DEBUG)Log.e(TAG, "in FFT(), DONE");
		}
		private void modifyScale_ratio(){
			if(selectedChannelTable.length==2){
				//basic rule: 
				//	1.pick two channnels
				//	2.subtract element[selectedChannelTable[0]-1].indexOfSumAlpha
				if(isThetaPressed){
					powerDifferenceOfTwoChannels_float=(float) (element[selectedChannelTable[0]-1].sumTheta[element[0].indexOfSumAlpha-1] /
							element[selectedChannelTable[1]-1].sumTheta[element[0].indexOfSumAlpha-1]);
				}
				else if(isAlphaPressed){
					powerDifferenceOfTwoChannels_float=(float)(element[selectedChannelTable[0]-1].sumAlpha[element[0].indexOfSumAlpha-1] / 
							element[selectedChannelTable[1]-1].sumAlpha[element[0].indexOfSumAlpha-1]);
				}
				else if(isBetaPressed){
					powerDifferenceOfTwoChannels_float=(float)(element[selectedChannelTable[0]-1].sumBeta[element[0].indexOfSumAlpha-1] / 
							element[selectedChannelTable[1]-1].sumBeta[element[0].indexOfSumAlpha-1]);
				}
				else
					powerDifferenceOfTwoChannels_float =0;
			}
			else{
				Log.e(TAG, "More than two channnels were selected");
			}
		}
		private void modifyScale_plus(){
			if(selectedChannelTable.length==2){
				//basic rule: 
				//	1.pick two channnels
				//	2.subtract element[selectedChannelTable[0]-1].indexOfSumAlpha
				if(isThetaPressed){
					powerDifferenceOfTwoChannels_float=(float)(element[selectedChannelTable[0]-1].sumTheta[element[0].indexOfSumAlpha-1] + 
							element[selectedChannelTable[1]-1].sumTheta[element[0].indexOfSumAlpha-1]);
				}
				else if(isAlphaPressed){
					powerDifferenceOfTwoChannels_float=(float)(element[selectedChannelTable[0]-1].sumAlpha[element[0].indexOfSumAlpha-1] + 
							element[selectedChannelTable[1]-1].sumAlpha[element[0].indexOfSumAlpha-1]);
				}
				else if(isBetaPressed){
					powerDifferenceOfTwoChannels_float=(float)(element[selectedChannelTable[0]-1].sumBeta[element[0].indexOfSumAlpha-1] + 
							element[selectedChannelTable[1]-1].sumBeta[element[0].indexOfSumAlpha-1]);
				}
				else
					powerDifferenceOfTwoChannels =0;
			}
			else{
				Log.e(TAG, "More than two channnels were selected");
			}	
		}
		private void modifyScale_subtract(){
			if(selectedChannelTable.length==2){
				//basic rule: 
				//	1.pick two channnels
				//	2.subtract element[selectedChannelTable[0]-1].indexOfSumAlpha
				if(isThetaPressed){
					powerDifferenceOfTwoChannels=(int)(element[selectedChannelTable[0]-1].sumTheta[element[0].indexOfSumAlpha-1] - 
							element[selectedChannelTable[1]-1].sumTheta[element[0].indexOfSumAlpha-1]);
				}
				else if(isAlphaPressed){
					powerDifferenceOfTwoChannels=(int)(element[selectedChannelTable[0]-1].sumAlpha[element[0].indexOfSumAlpha-1] - 
							element[selectedChannelTable[1]-1].sumAlpha[element[0].indexOfSumAlpha-1]);
				}
				else if(isBetaPressed){
					powerDifferenceOfTwoChannels=(int)(element[selectedChannelTable[0]-1].sumBeta[element[0].indexOfSumAlpha-1] - 
							element[selectedChannelTable[1]-1].sumBeta[element[0].indexOfSumAlpha-1]);
				}
				else
					powerDifferenceOfTwoChannels =0;
			}
			else{
				Log.e(TAG, "More than two channnels were selected");
			}
		}
		protected void onDraw(Canvas canvas){
			if(DEBUG)Log.e(TAG, "in onDraw!");
			//clear old canvas
			canvas.drawColor(Color.WHITE);
			paint.setStrokeWidth(1);
			paint.setStyle(Style.FILL);
			canvas.drawBitmap(bitmapAfter, null, rectForBitmap, paint);
			//draw three buttons, theta/alpha/beta
			if(isThetaPressed)
				canvas.drawBitmap(bitmapThetaw, null, rectForBitmapTheta,paint);
			else
				canvas.drawBitmap(bitmapThetag, null, rectForBitmapTheta,paint);
			if(isAlphaPressed)
				canvas.drawBitmap(bitmapAlphaw, null, rectForBitmapAlpha,paint);
			else
				canvas.drawBitmap(bitmapAlphag, null, rectForBitmapAlpha,paint);
			if(isBetaPressed)
				canvas.drawBitmap(bitmapBetaw, null, rectForBitmapBeta,paint);
			else
				canvas.drawBitmap(bitmapBetag, null, rectForBitmapBeta,paint);

			//paint.setColor(Color.rgb(180, 180, 180));
			for(int channel=0;channel<buffer.channels;channel++){
				if(element[channel].isSelected && element[channel].indexOfSumAlpha>1){
					if(isThetaPressed){
						
						//paint.setColor(pickColorByRatio(element[channel].sumTheta[element[0].indexOfSumAlpha-1],element[channel].meanTheta));
						//paint.setColor((int)(element[channel].sumTheta[element[0].indexOfSumAlpha-1]*(0xFF00FF00/element[channel].meanTheta)));
						//canvas.drawCircle(element[channel].picX+25, element[channel].picY+30, picChannelWidth-27, paint);
						//canvas.drawBitmap(element[channel].picPowerDensity, null,element[channel].rectf,paint);
					}
					else if(isAlphaPressed){
						//paint.setColor(pickColor(element[channel].meanAlpha,element[channel].tempAlphaMax));
						//paint.setColor(pickColor(element[channel].tempAlphaMax,element[channel].tempAlphaMax));
						//paint.setColor(pickColorByRatio(element[channel].sumAlpha[element[0].indexOfSumAlpha-1],element[channel].meanAlpha));
						//paint.setColor((int)(element[channel].sumAlpha[element[0].indexOfSumAlpha-1]*(0xFF00FF00/element[channel].meanAlpha)));
						//canvas.drawCircle(element[channel].picX+25, element[channel].picY+30, picChannelWidth-27, paint);
					}
					else if(isBetaPressed){
						//paint.setColor(pickColor(element[channel].meanAlpha,element[channel].meanAlpha));
						//paint.setColor(pickColorByRatio(element[channel].sumBeta[element[0].indexOfSumAlpha-1],element[channel].meanBeta));
						//paint.setColor((int)(element[channel].sumBeta[element[0].indexOfSumAlpha-1]*(0xFF00FF00/element[channel].meanBeta)));
						//canvas.drawCircle(element[channel].picX+25, element[channel].picY+30, picChannelWidth-27, paint);
					}
					else
						canvas.drawBitmap(element[channel].picWhite,null,element[channel].rectf,paint);;
				}
				else
					canvas.drawBitmap(element[channel].picGray,null,element[channel].rectf,paint);
			}
			//for plus, subtract,times10,divide10 button
			canvas.drawBitmap(bitmapPlus1, null, rectForBitmapPlus1,paint);
			canvas.drawBitmap(bitmapSubtract1, null, rectForBitmapSubtract1, paint);
			canvas.drawBitmap(bitmapTimes10, null, rectForBitmapTimes10,paint);
			canvas.drawBitmap(bitmapDivide10, null, rectForBitmapDivide10, paint);
			canvas.drawBitmap(bitmapPlus, null, rectForBitmapPlus,paint);
			canvas.drawBitmap(bitmapSubtract, null, rectForBitmapSubtract, paint);
			canvas.drawBitmap(bitmapRatiobydivide, null, rectForBitmapRatiobydivide,paint);
			canvas.drawBitmap(bitmapRatiobyplus, null, rectForBitmapRatiobyplus, paint);
			
			//for Pullball
			canvas.save();
			canvas.translate(755, 200);
			if(powerDifferenceOfTwoChannels_float>ratioBase){
				if(rectForBitmapBall.centerX()>=200)
					ballOffset = 0;
				else
					ballOffset +=10;
			}
			else if(powerDifferenceOfTwoChannels_float<ratioBase){
				if(rectForBitmapBall.centerX()<=-200)
					ballOffset = 0;
				else
					ballOffset -=10;
			}
			else
				ballOffset =0;
			rectForBitmapBall.offset(ballOffset, 0);
			canvas.drawBitmap(bitmapBall, null, rectForBitmapBall,paint);
			ballOffset=0;
			//rectForBitmapBall.offset(-ballOffset, 0);
			paint.setTextSize(20);
			//canvas.drawText(Float.toString(ratioBase), 700, 150, paint);
			/*if(powerDifferenceOfTwoChannels_float>200)
				powerDifferenceOfTwoChannels_float = 100;
			else if(powerDifferenceOfTwoChannels_float<-100)
				powerDifferenceOfTwoChannels_float = -100;*/
			canvas.restore();
			
			canvas.save();
			//for horizantal bar
			canvas.translate(505,200);
			paint.setColor(Color.GRAY);	
			paint.setStrokeWidth(5);
			paint.setStyle(Style.STROKE);
			canvas.drawRect(new RectF(0,0,500,100), paint);
			paint.setStrokeWidth(1);
			canvas.drawLine(250, 0, 250, 100, paint);
			//paint.setTextSize(30);
			paint.setTextSize(20);
			paint.setStyle(Style.FILL);
			if(ratioTag.equalsIgnoreCase("DIVIDE"))
				canvas.drawText("Approach: "+ element[selectedChannelTable[0]-1].channelName+"/"+element[selectedChannelTable[1]-1].channelName, 0, 200, paint);
			else
				canvas.drawText("Approach: "+ element[selectedChannelTable[0]-1].channelName+"+"+element[selectedChannelTable[1]-1].channelName, 0, 200, paint);
			canvas.drawText("BaseLine/Ratio: "+Float.toString(ratioBase)+" / "+Float.toString(powerDifferenceOfTwoChannels_float), 0, 250, paint);
			canvas.drawText("Avg. of "+baselineLength+"sec: "+baseline, 0, 300, paint);
			
			canvas.drawText(element[selectedChannelTable[1]-1].channelName, 0, 145, paint);//x axis
			canvas.drawText(element[selectedChannelTable[0]-1].channelName, 450, 145, paint);//x axis
			canvas.restore();
			
			//for color bar
			/*canvas.save();
			canvas.translate(150, 490);
			//paint.setTextSize(20);
			mDrawable.draw(canvas);
			paint.setColor(Color.BLACK);
			canvas.drawText("Low", 0, 25, paint);
			canvas.drawText("High", 180, 25, paint);
			canvas.restore();*/
			
			for(int channel=0;channel<Buffer.channels;channel++){
				if(element[channel].isSelected){
					//canvas.drawOval(element[channel].rectf, paint);
					canvas.drawBitmap(element[channel].picWhite,null,element[channel].rectf,paint);
				}
				else
					canvas.drawBitmap(element[channel].picGray,null,element[channel].rectf,paint);
			}
			setTitle("SkullmapAndPullball, "+buffer.getDataIndex()/60+":"+buffer.getDataIndex()%60);
		}
		private int pickColorByRatio(double value, double meanValue){
			int newValue = 0;
			float ratio = 0.5f; //50%
			msgToDisplay = "";
			if(value > ((1+ratio)*meanValue)){//red
				newValue = Color.rgb(255,0,0);
				msgToDisplay = "Red, "+value+", "+meanValue+", "+(value-meanValue);
			}
			else if((value <= (1+ratio)*meanValue) && (value > meanValue)){
				newValue = Color.rgb(255, 255, 0);//yellow
				msgToDisplay = "Yellow, "+value+", "+meanValue+", "+(value-meanValue);
			}
			else if(value < (ratio*meanValue)){
				newValue = Color.rgb(0, 0, 255);//deep blue
				msgToDisplay = "Deep Blue, "+value+", "+meanValue+", "+(meanValue - value);
			}
			else if((value >= ratio*meanValue) && (value<meanValue)){
				newValue = Color.rgb(0, 255, 255);//light blue
				msgToDisplay = "Light Blue, "+value+", "+meanValue+", "+(meanValue - value);
			}
			else{
				newValue = Color.rgb(0, 255, 0);//green
				msgToDisplay = "Green, "+meanValue+", "+(value-meanValue);
			}
			msgToDisplay+=", ch="+Integer.toString(selectedChannelTable[0]-1)+", mean= "+element[selectedChannelTable[0]-1].meanAlpha;	
			return newValue;
		}
		private int pickColor(double value, double meanValue){
			int newValue = 0;
			double ratio=0;
			String temp = "0";
			if(meanValue>1)
				ratio = ((Color.rgb(0, 255, 0))/meanValue);
			newValue = (int)(value*ratio);
			int retColor=Color.WHITE;
			if(newValue < Color.rgb(0, 0, 255)){
				retColor = Color.rgb(255, 0, 0);
				temp = "1";
			}
			else if(newValue < Color.rgb(0, 255, 0)){//
				retColor = Color.rgb(255, 255, 0);
				temp = "2";
			}
			else if(newValue<Color.rgb(0, 255, 255)){//
				retColor = Color.rgb(0, 255, 0);
				temp = "3";
			}
			else if(newValue < Color.rgb(255, 0, 0)){
				retColor = Color.rgb(0, 255, 255);
				temp = "4";
			}
			else {
				retColor = Color.rgb(0, 0, 255);
				temp = "5";
			}
			if(DEBUG)Log.i(TAG, "oriValue / newValue / retColor / temp /ratio/ maxValue= "+Integer.toHexString((int)value)+" / "+Integer.toHexString((int)newValue)+" / "+Integer.toHexString(retColor)+" / "+temp+" / "+ratio+" / "+(meanValue));
			msgToDisplay = "";
			//msgToDisplay = ("oriValue /newValue /retColor /temp /ratio/ maxValue= "+Integer.toHexString((int)value)+" / "+Integer.toHexString((int)newValue)+" / "+Integer.toHexString(retColor)+" / "+temp+" / "+ratio+" / "+Integer.toHexString((int)meanValue));
			
			return retColor;
		}
		/**
		Due to not every channel was selected, the yAxis of each channel should be adjusted accordingly.
		Arg: channel number
		Ret: the index, from zero, of selected channel in selectedChannelTable[]
		**/
		private int getSignalFrameHeightScale(int channelNumber){
			int result=1000;
			for(int i=0;i<selectedChannelTable.length;i++){
				if((selectedChannelTable[i]-1) == channelNumber){
					result = i+1;
					break;
				}
			}
			return result;
		}
		private void initial(){
			/*for(int i=0;i<selectedChannelTable.length;i++){
				selectedChannelTable[i] = i+1;
				element[i].isSelected = true;
			}*/
			//for C3
			selectedChannelTable[0] = 9;
			element[8].isSelected = true;
			//for C4
			selectedChannelTable[1] = 10;
			element[9].isSelected = true;
			for(int i=0;i<buffer.channels;i++){
				//selectedChannelTable[i]= i+1;
				//element[i].isSelected = true;
				if(i==0){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.fpzg);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.fpzw);
					element[i].setPicXY(259-25, 119-25,259-25+picChannelWidth, 119-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==1){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.fzg);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.fzw);
					element[i].setPicXY(259-25, 171-25,259-25+picChannelWidth, 171-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==2){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.f3g);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.f3w);
					element[i].setPicXY(190-25, 209-25,190-25+picChannelWidth, 209-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==3){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.f4g);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.f4w);
					element[i].setPicXY(328-25,209-25,328-25+picChannelWidth, 209-25+picChannelHeight);;
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==4){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.f7g);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.f7w);
					element[i].setPicXY(142-25, 182-25,142-25+picChannelWidth, 182-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==5){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.f8g);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.f8w);
					element[i].setPicXY(380-25, 182-25,380-25+picChannelWidth, 182-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==6){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.fczg);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.fczw);
					element[i].setPicXY(259-25, 231-25,259-25+picChannelWidth, 231-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==7){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.czg);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.czw);
					element[i].setPicXY(259-25, 290-25,259-25+picChannelWidth, 290-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==8){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.c3g);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.c3w);
					element[i].setPicXY(190-25, 290-25,190-25+picChannelWidth, 290-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==9){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.c4g);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.c4w);
					element[i].setPicXY(328-25, 290-25,328-25+picChannelWidth, 290-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==10){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.pzg);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.pzw);
					element[i].setPicXY(259-25, 361-25,259-25+picChannelWidth, 361-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==11){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.p3g);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.p3w);
					element[i].setPicXY(190-25, 361-25,190-25+picChannelWidth, 361-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==12){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.p4g);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.p4w);
					element[i].setPicXY(328-25, 361-25,328-25+picChannelWidth, 361-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==13){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.t5g);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.t5w);
					element[i].setPicXY(149-25, 405-25,149-25+picChannelWidth, 405-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==14){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.t6g);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.t6w);
					element[i].setPicXY(380-25, 405-25,380-25+picChannelWidth, 405-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
				else if(i==15){
					element[i].picGray = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.ozg);
					element[i].picWhite = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.ozw);
					element[i].setPicXY(259-25, 455-25,259-25+picChannelWidth, 455-25+picChannelHeight);
					element[i].picPowerDensity = BitmapFactory.decodeResource(getResources(), 
				               R.drawable.powerdensity);
				}
			}
		}
		private final Handler mHandler = new Handler() {
	        public void handleMessage(Message msg) {
	            switch (msg.what) {
	            case 0://repaint            	
	            	invalidate();
	           	 break;
	            case 1://fill in data
	            	setData((Vector)msg.obj);
	            	//if(DEBUG)Log.e(TAG, "in Handler!");
	           	 break;
	            case 2:
	           	 break;
	            }
	        }
	    };
		public boolean onTouch(View v, MotionEvent e) {
			handleTwoFingers(e);
			handleOneFingerSwipe(e);
			return false;//if return true, the onLongClick can't work.
		}
		
		private void handleOneFingerSwipe(MotionEvent event){
			
			int action = event.getAction();
			int actionCode = action & MotionEvent.ACTION_MASK;
			if(actionCode == MotionEvent.ACTION_DOWN && event.getPointerCount()==1){
				oriXAxis = event.getX();
				oriYAxis = event.getY();
				if(DEBUG)Log.e(TAG, "oriXAxis= "+oriXAxis+"\n");
				//msgToDisplay = "";
				//msgToDisplay = oriXAxis+"/"+oriYAxis;
				handleSelectedChannel(oriXAxis, oriYAxis);				
			}
			if(actionCode == MotionEvent.ACTION_MOVE &&event.getPointerCount()==1){
				if(event.getX()>oriXAxis && (event.getX()-oriXAxis >MIN_SLIDE_DISTANCE)){//swipe to right
					finish();
					startActivity(new Intent(SkullmapPullballActivity.this, PowerDensityandSkullmapActivity.class));	
					if(DEBUG)Log.e(TAG, "SWIPE TO RIGHT! /oriXAxis= "+oriXAxis+" / "+event.getX()+"\n");
				}
				else if(event.getX()<oriXAxis && (oriXAxis-event.getX() >MIN_SLIDE_DISTANCE)){//swipe to left.
					//finish();
					//startActivity(new Intent(PowerDensity.this, CCADomainActivity.class));		
					if(DEBUG)Log.e(TAG, "SWIPE TO LEFT! /oriXAxis= "+oriXAxis+" / "+event.getX()+"\n");
				}
				//swipe up, turn the Filter
				else if(event.getY()<oriYAxis &&(oriYAxis-event.getY()>MIN_SLIDE_DISTANCE)){
					filterTag = true;
					popMsg.makeText( this.getContext(), R.string.Enable_Band_Pass_Filter,popMsg.LENGTH_SHORT).show();
				}
				//swipe down, turn off the filter
				else if(event.getY()>oriYAxis &&(event.getY()-oriYAxis>MIN_SLIDE_DISTANCE)){
					filterTag = false;
					popMsg.makeText( this.getContext(), R.string.Disable_Band_Pass_Filter,popMsg.LENGTH_SHORT).show();
				}
			}
		}
		private void handleTwoFingers(MotionEvent event) {
			float newDistanceOfFingers;
			int action = event.getAction();
			int actionCode = action & MotionEvent.ACTION_MASK;
			//if(DEBUG)Log.e(TAG, "**********In handleTwoFingers()");
			if(actionCode == MotionEvent.ACTION_POINTER_DOWN && event.getPointerCount()==2){
				oriDistanceOfFingers = FloatMath.sqrt((event.getX(0)-event.getX(1)) * (event.getX(0)-event.getX(1)) + 
						(event.getY(0)-event.getY(1)) * (event.getY(0)-event.getY(1)));
				//if(DEBUG)Log.e(TAG,"**********ori= "+oriDistanceOfFingers);
			}
			if(actionCode == MotionEvent.ACTION_MOVE &&event.getPointerCount()==2){
				newDistanceOfFingers = FloatMath.sqrt((event.getX(0)-event.getX(1)) * (event.getX(0)-event.getX(1)) + 
						(event.getY(0)-event.getY(1)) * (event.getY(0)-event.getY(1)));
				Log.e(TAG,"**********new= "+newDistanceOfFingers);
				if(newDistanceOfFingers < oriDistanceOfFingers ){
					if(xAxisExtend>0&& newDistanceOfFingers>MIN_SLIDE_DISTANCE){
						//xAxisExtend--;
						//msgToDisplay = "Zoom Out";	
						//if(DEBUG)Log.e(TAG,"CCCCCCCCCc");
					}
					//popMsg.makeText( this.getContext(), R.string.ZoomOut_text,popMsg.LENGTH_SHORT).show();
					
				}
				if(newDistanceOfFingers > oriDistanceOfFingers ){
					if(xAxisExtend<5 && newDistanceOfFingers>MIN_SLIDE_DISTANCE){
						//xAxisExtend++;
						//msgToDisplay = "Zoom In";
						//if(DEBUG)Log.e(TAG,"DDDDDDDDDD");
					}
					//popMsg.makeText(getContext(), R.string.ZoomIn_text,popMsg.LENGTH_SHORT).show();
					
				}
			}
		}
		private void handleSelectedChannel(float x, float y){
			synchronized(this){
				//extract which channel was selected
				int selectedChannel = -1;// = ((int) (x%buffer.channels))+1;
				for(int i=0;i<buffer.channels;i++){
					if(element[i].rectf.left<x && element[i].rectf.right>x && element[i].rectf.top<y && element[i].rectf.bottom>y){
						//msgToDisplay +="##"+element[0].rectf.left+"/"+element[0].rectf.right+"/"+element[0].rectf.top+"/"+element[0].rectf.bottom;
						selectedChannel = i+1;
						//baseLineSecondTag = false;
						break;
					}
				}
				if(x<(picChannelWidth+20) && y>0 && y<(picChannelHeight+20))//theta Pressed,
					if(isThetaPressed != (!isThetaPressed)){
						isThetaPressed =!isThetaPressed;
						isAlphaPressed = false;
						isBetaPressed = false;
					}
				if(x<(picChannelWidth+20) && y>(picChannelHeight+20) && y<(picChannelHeight+20)*2)//alpha Pressed,
					if(isAlphaPressed != (!isAlphaPressed)){
						isAlphaPressed = !isAlphaPressed;
						isThetaPressed = false;
						isBetaPressed = false;
					}
				if(x<(picChannelWidth+20) && y>(picChannelHeight+20)*2 && y<(picChannelHeight+20)*3)//beta Pressed,
					if(isBetaPressed != (!isBetaPressed)){
						isBetaPressed =! isBetaPressed;
						isThetaPressed = false;
						isAlphaPressed = false;
					}
				//for plus,subtract,times10,divide10 bitmap
				if(x>650 && x<700 && y>0 && y<50)
					ratioBase +=1;
				if(x>750 && x<800 && y>0 && y<50)
					if(ratioBase>=1)
						ratioBase -=1;
				if(x>650 && x<700 && y>50 && y<100)
					ratioBase *=10;
				if(x>750 && x<800 && y>50 && y<100)
					if(ratioBase>=10)
						ratioBase /=10;
				if(x>650 && x<700 && y>100 && y<150)
					ratioBase +=0.1;
				if(x>750 && x<800 && y>100 && y<150)
					if(ratioBase>=0.1)
						ratioBase -=0.1;	
				if(x>650 && x<700 && y>150 && y<200){
					baselineLength = element[0].indexOfSumAlpha+10;
					ratioTag = "DIVIDE";
				}
				if(x>750 && x<800 && y>150 && y<200){
					baselineLength = element[0].indexOfSumAlpha+10;
					ratioTag= "PLUS";
				}
				/*if(DEBUG){
					Log.e(TAG, "///////////ORI////////////");
					for(int i=0;i<4;i++){
						Log.e(TAG, "selectedChannelTable["+i+"]= "+selectedChannelTable[i]);
					}
					for(int i=0;i<buffer.channels;i++){
						if(element[i].isSelected)
							Log.e(TAG, "selected channel= "+(i+1));
					}
					Log.e(TAG, "///////////ORI////////////////");
				}*/
				if(selectedChannel!=-1){
					if(!element[selectedChannel-1].isSelected){
						nextIndexSelectedChannelTable++;
						
						if(DEBUG)Log.e(TAG, "selectedChannel= "+selectedChannel+", nextIndexSelectedChannelTable= "+nextIndexSelectedChannelTable);
						
						//update color on skull map
						
						//update the selected channel table and element[].isSelected
						if(nextIndexSelectedChannelTable>selectedChannelTable.length){
							element[selectedChannelTable[0]-1].isSelected = false;
							element[selectedChannel-1].isSelected = true;
							nextIndexSelectedChannelTable=1;
							selectedChannelTable[nextIndexSelectedChannelTable-1] = selectedChannel;
						}
						else{
							if(selectedChannelTable[nextIndexSelectedChannelTable-1]>0)
								if(element[selectedChannelTable[nextIndexSelectedChannelTable-1]-1].isSelected)
									element[selectedChannelTable[nextIndexSelectedChannelTable-1]-1].isSelected = false;
							selectedChannelTable[nextIndexSelectedChannelTable-1] = selectedChannel;
							element[selectedChannel-1].isSelected = true;
						}
					}
					//refreshScreen();//refresh the signal screen
					/*if(DEBUG){
						Log.e(TAG, "///////////AFTER////////////////");
						for(int i=0;i<4;i++){
							Log.e(TAG, "selectedChannelTable["+i+"]= "+selectedChannelTable[i]);
						}
						for(int i=0;i<buffer.channels;i++){
							if(element[i].isSelected)
								Log.e(TAG, "selected channel= "+(i+1));
						}
						Log.e(TAG, "///////////AFTER////////////////");
					}*/
				}
			}
		}
		private void refreshScreen(){
			for(int channel=0;channel<buffer.channels;channel++){
				element[channel].indexOfSumAlpha = 0;
				element[channel].tempAlphaMax = 0;
				element[channel].tempBetaMax = 0;
				element[channel].tempThetaMax = 0;
			}
		}
		public boolean onLongClick(View v) {
			/*//msgToDisplay = "11111111111";
			new AlertDialog.Builder(this.getContext())
	        //.setIcon(R.drawable.alert_dialog_icon)
	        .setTitle(R.string.app_name)
	        .setSingleChoiceItems(R.array.select_dialog_items2, 0, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	            	switch(whichButton){
	            	case 0:
	            		selectionForNextDisplay = 0;//button 1 pressed, Time mode display
	            		break;
	            	case 1:
	            		selectionForNextDisplay = 1;//button 2 pressed, Frequency mode display
	            		break;
	            	case 2:
	            		selectionForNextDisplay = 2;//button 3 pressed, CCA display
	            		break;
	            	case 3:
	            		selectionForNextDisplay = 3;//button 4 pressed, Debug mode
	            		break;
	            	}
	            }
	        })
	        .setPositiveButton(R.string.timeDomainDialog_button_ok, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	            	if(selectionForNextDisplay !=-1){
	            		msgToDisplay = "selectionForNextDisplay"+"/pressed";
	            	}
	            	selectionForNextDisplay =-1;//in case user didn't press any of mode to display, and press OK/CANCEL only.
	            }
	        })
	        .setNegativeButton(R.string.timeDomainDialog_button_cancel, new DialogInterface.OnClickListener() {
	            public void onClick(DialogInterface dialog, int whichButton) {
	            	msgToDisplay += "3/";	
	                // User clicked No so do some stuff 
	            }
	        })
	       .show();
			if(DEBUG)Log.e(TAG, "onLongClick!\n");*/
			return true;
		}
	}
}
