// (C)2007 Attila Kovacs <attila@submm.caltech.edu>

// 

import java.io.*;
import java.util.*;
import java.text.*;

public class APEXSZPixel extends LabocaPixel {
	
	public APEXSZPixel(int backendChannel) {
		super(backendChannel);
	}
	
	public static void markBads(LabocaPixel[] channel) {}
	
	public String gainString(DecimalFormat df) {
		String text = 
			df.format(gain) + "  " +
			"\t" + df.format(waferGain) + "  " +
			"\t" + df.format(ampGain) + "  "; 

		return text;
	}
	
	@Override
	public void parseGains(StringTokenizer tokens) {
		gain = Double.parseDouble(tokens.nextToken());
		boxGain = Double.parseDouble(tokens.nextToken());
		ampGain = Double.parseDouble(tokens.nextToken());
	}
	
	public String gainHeader() {
		return "gain\t\tGwafer\t\tGsquid";
	}
		
	
	public void wedgeOnlyNeighbours() {
		for(int i=0; i<neighbours.size();) {
			if(neighbours.get(i).wafer != wafer) neighbours.remove(i);
			else i++;			
		}
		
	}
	
	public static void fillWiringInfo(LabocaPixel[] channel) {	
		LabocaPixel.fillWiringInfo(channel);
		
		double minY = 0.0, maxY = 0.0;
		for(int c=0; c<channel.length; c++) {
			if(channel[c].position.y < minY) minY = channel[c].position.y;
			if(channel[c].position.y > maxY) maxY = channel[c].position.y;
		}
		
		double binY = (maxY-minY) / 11.99;
		
		for(int c=0; c<channel.length; c++) channel[c].region = (int) ((channel[c].position.y - minY) / binY);
		
	}
	
	//          01    2 34     5
	// Readout [e1-f5]:[ra-rb][1-8]
	// Squid   [e1-f3]:sa[2-8]
	//          01    234 5
	
	public static void readWiring(String fileName) throws IOException {	
		int channels = 331;
		
		boxForChannel = new int[channels];
		cableForChannel = new int[channels];
		waferForChannel = new int[channels];
		ampForChannel = new int[channels];
		pinForChannel = new int[channels];
		
		String[] waferNames = { "e1", "e5", "e8", "ed", "f0", "f3" };
		int boxStartAddress = Integer.decode("0xe1");
		
		BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(fileName)));
		String line;
		while((line = in.readLine()) != null) if(line.length() > 0) if(line.charAt(0) != '#') {
			StringTokenizer tokens = new StringTokenizer(line);
			tokens.nextToken();
			String readoutAddress = tokens.nextToken();
			String squidAddress = tokens.nextToken();
			int c = Integer.parseInt(tokens.nextToken()) - 1;
			
			boxForChannel[c] = Integer.decode("0x" + readoutAddress.substring(0,2)) - boxStartAddress;
			cableForChannel[c] = 2*boxForChannel[c] + (readoutAddress.charAt(4) - 'a'); 
			pinForChannel[c] = readoutAddress.charAt(5);
			
			String waferName = squidAddress.substring(0, 2);
			
			for(int g=0; g<waferNames.length; g++) if(waferName.equalsIgnoreCase(waferNames[g])) {
				waferForChannel[c] = g; 
				break;
			}
			
			ampForChannel[c] = 7 * waferForChannel[c] + Integer.parseInt(squidAddress.substring(5)) - 2;			
		}
		
	}	
}
