/*******************************************************************************
 * Copyright (c) 2010 Attila Kovacs <attila_kovacs@post.harvard.edu>.
 * All rights reserved. 
 * 
 * This file is part of crush.
 * 
 *     crush is free software: you can redistribute it and/or modify
 *     it under the terms of the GNU General Public License as published by
 *     the Free Software Foundation, either version 3 of the License, or
 *     (at your option) any later version.
 * 
 *     crush is distributed in the hope that it will be useful,
 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *     GNU General Public License for more details.
 * 
 *     You should have received a copy of the GNU General Public License
 *     along with crush.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * Contributors:
 *     Attila Kovacs <attila_kovacs@post.harvard.edu> - initial API and implementation
 ******************************************************************************/
// Copyright (c) 2009 Attila Kovacs 

package crush.gismo;

import crush.*;
import util.*;

import nom.tam.fits.*;

public class GismoIntegration extends Integration<Gismo, GismoFrame> implements GroundBased {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6513008414302600380L;
	
	HorizontalCoordinates reuseTrackingCenter = new HorizontalCoordinates();
	
	public GismoIntegration(GismoScan parent) {
		super(parent);
	}	
	
	@Override
	public void validate() {
		if(hasOption("tau.225ghz")) setTau225GHz(option("tau.225ghz").getDouble());
		else if(!Double.isNaN(((GismoScan) scan).tau225GHz)) setTau225GHz(((GismoScan) scan).tau225GHz);
		super.validate();
	}
	
	public void setTau225GHz(double value) {
		((GismoScan) scan).tau225GHz = value;
		double pwv = 20.2 * value - 0.18; // Based on the CSO ATM
		System.err.println("   tau(225GHz) = " + Util.f3.format(value) + " --> Estimated PWV: " + Util.f1.format(pwv) + " mm.");
		double tau = (0.0003 * pwv + 0.0202) * pwv + 0.009; // Based on the CSO ATM
		setZenithTau(tau);		
	}
	
	@Override
	public GismoFrame getFrameInstance() {
		return new GismoFrame((GismoScan) scan);
	}
	
	@Override
	public int getNodPhase() {
		// TODO Auto-generated method stub
		return 0;
	}
	
	protected void read(BinaryTableHDU hdu) throws IllegalStateException, HeaderCardException, FitsException {
		GismoScan gismoScan = (GismoScan) scan;
		
		int records = hdu.getAxes()[0];

		System.err.println(" Processing scan data:");
		
		System.err.println("   Reading " + records + " frames.");
	
		Header header = hdu.getHeader();
		
		instrument.integrationTime = instrument.samplingInterval = header.getDoubleValue("CDELT1") * Unit.ms;
		System.err.println("   Sampling at " + Util.f1.format(instrument.integrationTime / Unit.ms) + " ms ---> " 
				+ Util.f1.format(instrument.samplingInterval * records / Unit.min) + " minutes.");
		
		clear();
		ensureCapacity(records);
		
		final int iRA = hdu.findColumn("RA");
		final int iDEC = hdu.findColumn("DEC");
		final int iAZ = hdu.findColumn("AZ");
		final int iEL = hdu.findColumn("EL");
		final int iAZE = hdu.findColumn("AZ_ERROR");
		final int iELE = hdu.findColumn("EL_ERROR");
		//final int iPA = hdu.findColumn("PARALLACTIC_ANGLE");
		final int iMJD = hdu.findColumn("MJD");
		//final int iUT = hdu.findColumn("UT");
		final int iLST = hdu.findColumn("LST");
		//final int iLT = hdu.findColumn("LABVIEWTIME");
		final int iSN = hdu.findColumn("FRAME_COUNTER");
		//final int iRAO = hdu.findColumn("RAO");
		//final int iDECO = hdu.findColumn("DECO");
		//final int iAZO = hdu.findColumn("AZO");
		//final int iELO = hdu.findColumn("ELO");
		//final int iFlag = hdu.findColumn("Celestial");
		//final int iTRK = hdu.findColumn("Tracking");
		final int iCHO = hdu.findColumn("CHOP_OFFSET"); // TODO is it used?
		final int iCAL = hdu.findColumn("CalFlag"); // 0=none, 1=shutter, 2=ivcurve
		
		
		final int iDAC = hdu.findColumn("DAC");
		//final int iSAE = hdu.findColumn("SAE");
		final int iNS = hdu.findColumn("NUMBER_OF_SAMPLES");
		//final int iDT = hdu.findColumn("DIODE_TEMPERATURES");
		//final int iRT = hdu.findColumn("RESISTOR_TEMPERATURES"); // TODO One of these is cold plate temp.
		//final int iDV = hdu.findColumn("DIODE_VOLTS");
		//final int iRO = hdu.findColumn("RESISTOR_OHMS");
		//final int iMRT = hdu.findColumn("MAIN_RESISTOR_TEMPERATURE"); // TODO is this cold plate?
		final int iSDI = hdu.findColumn("SUMMARIZED_DIGITAL_INPUT");
		
		HorizontalCoordinates trackingCenter = new HorizontalCoordinates();
		EquatorialCoordinates apparent = new EquatorialCoordinates();
		Precession catalogToApparent = null;
			
		for(int i=0; i<records; i++) {		
			GismoFrame frame = new GismoFrame(gismoScan);
			Object[] row = hdu.getRow(i);

			//final double UT = (((double[]) row[iUT])[0] * Unit.sec) % Unit.day;
			frame.MJD = ((double[]) row[iMJD])[0];
			frame.samples = ((int[]) row[iNS])[0];
			
			byte[] sdi = (byte[]) row[iSDI];
			for(int bit=0; bit<6; bit++) if(sdi[bit] > 0) frame.digitalFlag |= 1 << bit;
			
			//frame.diodeT = (float[]) row[iDT];
			//frame.resistorT = (float[]) row[iRT];
			//frame.diodeV = (float[]) row[iDV];
			
			frame.parseData((float[][]) row[iDAC]);

			// This is the tracking center only...
			// It's in the same epoch as the scan (checked!)
			apparent.setLongitude(((float[])row[iRA])[0] * Unit.hourAngle);
			apparent.setLatitude(((float[])row[iDEC])[0] * Unit.deg);
			if(catalogToApparent == null) {
				CoordinateEpoch apparentEpoch = new JulianEpoch();
				apparentEpoch.setMJD(frame.MJD);
				catalogToApparent = new Precession(scan.equatorial.epoch, apparentEpoch);
			}
			catalogToApparent.precess(apparent);
		
			final double AZE = ((float[])row[iAZE])[0] * Unit.arcsec;
			final double ELE = ((float[])row[iELE])[0] * Unit.arcsec;	
			
			
			frame.horizontal = new HorizontalCoordinates(
					((float[])row[iAZ])[0] * Unit.deg + AZE,
					((float[])row[iEL])[0] * Unit.deg + ELE);
			
			frame.calcParallacticAngle();
			
			frame.LST = ((float[])row[iLST])[0] * Unit.sec;
		
			
			//frame.labviewTime = ((double[])row[iLT])[0] * Unit.sec;
			frame.frameNumber = ((int[])row[iSN])[0];
				
			// Read the chopped position data...
			frame.chopperPosition.x = ((float[])row[iCHO])[0] * Unit.arcsec;
			
			// Add the chopper offet to the actual coordinates as well...
			frame.horizontal.x += frame.chopperPosition.x / frame.horizontal.cosLat;
			
			// Calculate the horizontal offset	
			apparent.toHorizontal(trackingCenter, scan.site, frame.LST);
			frame.horizontalOffset = frame.horizontal.getOffsetFrom(trackingCenter);
			
			// Force recalculation of the equatorial coordinates...
			frame.equatorial = null;
			
			if(iCAL > 0) frame.calFlag = ((int[])row[iCAL])[0];
			
			if(frame.isValid())	add(frame);
			else add(null);	
		}
	
	}
	
	

}
