// Collection of code snippets by Arne Vajhøj 
// (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) 
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;

public class CsvTest extends Test {
    private BufferedReader br = null;
    private PrintStream ps = null;
    public CsvTest(InputStream is) {
        br = new BufferedReader(new InputStreamReader(new BufferedInputStream(is)));
    }
    public CsvTest(OutputStream os) {
        ps = new PrintStream(new BufferedOutputStream(os));
    }
    public void writeRec(Data o) {
        ps.println(o.getIv() + "," + o.getXv() + "," + o.getSv());
    }
    public Data readRec() throws TestException {
        try {
            String line = br.readLine();
            int ix1 = line.indexOf(',');
            int ix2 = line.indexOf(',', ix1 + 1);
            int iv = Integer.parseInt(line.substring(0, ix1));
            double xv = Double.parseDouble(line.substring(ix1 + 1, ix2));
            String sv = line.substring(ix2 + 1);
            Data o = new Data(iv, xv, sv);
            return o;
        } catch (NumberFormatException e) {
            throw new TestException(e.getMessage());
        } catch (IOException e) {
            throw new TestException(e.getMessage());
        }
    }
    public void close() throws TestException {
        try {
            if(br != null) {
                br.close();
            }
            if(ps != null) {
                ps.close();
            }
        } catch (IOException e) {
            throw new TestException(e.getMessage());
        }
    }
}
