/* Generated by Together */

package Sesame2;
import java.util.Vector;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.io.IOException;

public class SAFFormatWaveform extends multipleWaveform
	{
	double		samplingFreq;
	int		numberOfPoints;
	int 	year;
  int		month;
  int		day;
  int		hour;
  int		minute;
  double	second;
	char	amplitudeType;
  private String stationName;
  private String	sensorName;
	private String	ch0;
  private String	ch1;
  private String	ch2;
  private String  units;
  private boolean hasGain;
  private double gain;

    FileInputStream fileIn;
    BufferedReader in;

	public SAFFormatWaveform()
		{
    hasGain = false;
    setSensorName(new String(""));
		setCh0(new String(""));
		setCh1(new String(""));
		setCh2(new String(""));
    setUnits(new String(""));
		}

	public int loadFile(String filename)
		{
		String inputLine;
        filename = filename.replace('\"',' ');
        filename = filename.trim();
		System.out.println("Reading the output file..." + filename);
		String data = "";
		try
			{
            boolean done;

            done = false;

            int		ret;

            ret = loadHeader(filename);

            if (ret != 0)
                return ret;

            // read wave data
            int 			i;
            StreamTokenizer streamTokenizer = new StreamTokenizer (in);

            singleWaveform		comp;
            double				[] pts1;
            double				[] pts2;
            double				[] pts3;

            pts1 = new double [numberOfPoints];
            pts2 = new double [numberOfPoints];
            pts3 = new double [numberOfPoints];

            streamTokenizer.parseNumbers();
          	streamTokenizer.wordChars(33, 255);
            streamTokenizer.whitespaceChars(1, 32);

            streamTokenizer.nextToken();
            
            for (i = 0; i < numberOfPoints; i++)
              {
              if (streamTokenizer.ttype == StreamTokenizer.TT_NUMBER)
                pts1 [i] = streamTokenizer.nval;

              streamTokenizer.nextToken();
              if (streamTokenizer.ttype == StreamTokenizer.TT_WORD)
                {
                pts1 [i] *= Math.pow(10.0 , Double.parseDouble (streamTokenizer.sval.substring(1)));
                streamTokenizer.nextToken();
                }

              if (streamTokenizer.ttype == StreamTokenizer.TT_NUMBER)
                pts2 [i] = streamTokenizer.nval;

              streamTokenizer.nextToken();
              if (streamTokenizer.ttype == StreamTokenizer.TT_WORD)
                {
                pts2 [i] *= Math.pow(10.0 , Double.parseDouble (streamTokenizer.sval.substring(1)));
                streamTokenizer.nextToken();
                }

              if (streamTokenizer.ttype == StreamTokenizer.TT_NUMBER)
                pts3 [i] = streamTokenizer.nval;

              streamTokenizer.nextToken();
              if (streamTokenizer.ttype == StreamTokenizer.TT_WORD)
                {
                pts3 [i] *= Math.pow(10.0 , Double.parseDouble (streamTokenizer.sval.substring(1)));
                streamTokenizer.nextToken();
                }
              }

            comp = new singleWaveform ();
            comp.setYear(year);
            comp.setMonth(month);
            comp.setDay(day);
            comp.setHour(hour);
            comp.setMinute(minute);
            comp.setSeconds(second);
            comp.setSamplingFreq(samplingFreq);
            comp.setAmplitudeType(amplitudeType);
            comp.setUnits(units);

            comp.setChannelName(getSensorName() + getCh0());
            Vector v1 = new Vector();
            Vector v2 = new Vector();
            Vector v3 = new Vector();
            int j=0;
            // removin offet zero
            double med1=0;
            double med2=0;
            double med3=0;
            double max1=pts1[0];
            double max2=pts2[0];
            double max3=pts3[0];
            double min1=max1;
            double min2=max2;
            double min3=max3;
            for( j=0; j< numberOfPoints; ++j) 
            {
              if( max1 < pts1[j] ) max1 = pts1[j];
              if( max2 < pts2[j] ) max2 = pts2[j];
              if( max3 < pts3[j] ) max3 = pts3[j];
              if( min1 > pts1[j] ) min1 = pts1[j];
              if( min2 > pts2[j] ) min2 = pts2[j];
              if( min3 > pts3[j] ) min3 = pts3[j];
           
            }
            if ((max1<0) || (max2<0) || (max3<0) ||
               (min1>0) || (min2>0) || (min3>0)) {
                med1 = (max1 + min1)/2.0;
                med2 = (max2 + min2)/2.0;            
                med3 = (max3 + min3)/2.0;
            }
            for( j=0; j< numberOfPoints; ++j) 
            {
              v1.addElement(new Double(pts1[j]-med1));
              v2.addElement(new Double(pts2[j]-med2));
              v3.addElement(new Double(pts3[j]-med3));
            }

            comp.setDataPoints(v1);
            this.addSingleTrace(comp);

            comp = new singleWaveform ();
            comp.setYear(year);
            comp.setMonth(month);
            comp.setDay(day);
            comp.setHour(hour);
            comp.setMinute(minute);
            comp.setSeconds(second);
            comp.setSamplingFreq(samplingFreq);
            comp.setAmplitudeType(amplitudeType);
            comp.setChannelName(getSensorName() + getCh1());
            comp.setDataPoints(v2);
            comp.setUnits(units);
            this.addSingleTrace(comp);

            comp = new singleWaveform ();
            comp.setYear(year);
            comp.setMonth(month);
            comp.setDay(day);
            comp.setHour(hour);
            comp.setMinute(minute);
            comp.setSeconds(second);
            comp.setSamplingFreq(samplingFreq);
            comp.setAmplitudeType(amplitudeType);
            comp.setChannelName(getSensorName() + getCh2());
          	comp.setDataPoints(v3);
            comp.setUnits(units);
            this.addSingleTrace(comp);

            in.close();
          	System.out.println("done");
			}
		catch (IOException Ex)
			{
			System.out.println(Ex.getMessage());
			return -1;
			}
        catch (Exception Ex)
			{
			System.out.println(Ex.getMessage());
			return -1;
			}

		return 0;
		}

	public int saveFile(String filename)
		{
		return 0;
		}

    public int readInt(String inputLine)
		{
		inputLine = inputLine.substring (inputLine.lastIndexOf(new String ("=")) + 1);
		inputLine = inputLine.trim();

        return Integer.parseInt (inputLine);
		}

    public double readDouble(String inputLine)
		{
		inputLine = inputLine.substring (inputLine.lastIndexOf(new String ("=")) + 1);
		inputLine = inputLine.trim();

        return Double.parseDouble (inputLine);
		}

    public String readString (String inputLine)
		{
        inputLine = inputLine.substring (inputLine.lastIndexOf(new String ("=")) + 1);
		inputLine = inputLine.trim();

        return inputLine;
		}

    public void readDate (String inputLine)
		{
        inputLine = inputLine.substring (inputLine.lastIndexOf(new String ("=")) + 1);
		inputLine = inputLine.trim();

        year = Integer.parseInt (inputLine.substring (0 , 4));
        inputLine = inputLine.substring (4).trim ();
        month = Integer.parseInt (inputLine.substring (0 , 2).trim ());
        inputLine = inputLine.substring (2).trim ();
        day = Integer.parseInt (inputLine.substring (0 , 2).trim ());
		inputLine = inputLine.substring (2).trim ();
        hour = Integer.parseInt (inputLine.substring (0 , 2).trim ());
        inputLine = inputLine.substring (2).trim ();
        minute = Integer.parseInt (inputLine.substring (0 , 2).trim ());
        inputLine = inputLine.substring (2).trim ();
        second = Double.parseDouble (inputLine.trim ());
		}

    public int loadHeader (String filename)
    	{
        String inputLine;
    		filename = filename.replace('\"',' ');
        filename = filename.trim();
		System.out.println("Reading the output file header..." + filename);
		String data = "";
        try
        	{
        	fileIn = new FileInputStream(filename);
			in = new BufferedReader(new InputStreamReader(fileIn));

             boolean done;

            done = false;

            // read data parameters
			while (((inputLine = in.readLine()) != null) && !done)
				{
				if (inputLine.length() < 2)
                    continue;

				if (inputLine.indexOf("####") == 0)		// data follows...
                    break;

        // parse the parameters
        String    originalInput;
        originalInput = inputLine;
				inputLine = inputLine.toUpperCase();

				if (inputLine.charAt(0) == '#')		// ignore comments
                    continue;

        if (inputLine.indexOf("UNITS") == 0)
					units = readString (originalInput);

        if (inputLine.indexOf("GAIN") == 0)
					{
          gain = readDouble (inputLine);
          hasGain = true;
          }

				if (inputLine.indexOf("SAMP_FREQ") == 0)
                    samplingFreq = readDouble (inputLine);

                if (inputLine.indexOf("NDAT") == 0)
					numberOfPoints = readInt (inputLine);

                if (inputLine.indexOf("START_TIME") == 0)
                    readDate (inputLine);

                if (inputLine.indexOf("SENSOR_TYPE") == 0)
					amplitudeType = readString (inputLine).charAt(0);

                if (inputLine.indexOf("SENSOR_NAME") == 0)
                    setSensorName(readString(inputLine));

                if (inputLine.indexOf("STA_CODE") == 0)
                    setStationName(readString(inputLine));

                if (inputLine.indexOf("CH0_ID") == 0)
                	setCh0(readString(inputLine));

                if (inputLine.indexOf("CH1_ID") == 0)
                    setCh1(readString(inputLine));

                if (inputLine.indexOf("CH2_ID") == 0)
                    setCh2(readString(inputLine));
				}
        	}
        catch (IOException Ex)
			{
			System.out.println(Ex.getMessage());
			return -1;
			}
        catch (Exception Ex)
			{
			System.out.println(Ex.getMessage());
			return -1;
			}

        return 0;
    	}

	public String getCh0()
		{
		return ch0;
		}

	public void setCh0(String ch0)
		{
		this.ch0 = ch0;
		}

	public String getCh1()
		{
		return ch1;
		}

	public void setCh1(String ch1)
		{
		this.ch1 = ch1;
		}

	public String getCh2()
		{
		return ch2;
		}

	public void setCh2(String ch2)
		{
		this.ch2 = ch2;
		}

	public String getSensorName()
		{
		return sensorName;
		}

	public void setSensorName(String sensorName)
		{
		this.sensorName = sensorName;
		}

	public String getStationName()
		{
		return stationName;
		}

	public void setStationName(String stationName)
		{
		this.stationName = stationName;
		}

  public String getUnits()
    {
    return units;    
    }

  public void setUnits(String un)
    {
    this.units = un;
    }

  public  double getFreqSampleMax() 
    {
    return samplingFreq;
    }
	}