/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package usda.weru.util.windgen;

import de.schlichtherle.io.File;
import de.schlichtherle.io.FileReader;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import org.apache.log4j.Logger;


/**
 *
 * @author wjr
 */
public class ExtractStationFromWDB {
    private static final Logger LOGGER = Logger.getLogger(MakeInterpolatedStation.class);

    static String wdbName = "c:/weps.svn/weps.install/db/wind_gen/wind_gen_his_upper_US.wdb";
    static String testStat = "722615";
    static String outDir = "c:/weps.svn/weps.install/test";
    static int linesToCopy = 212;       // one less than actual since 1st is already in inpLin

    public ExtractStationFromWDB(File wdb, String outDir, String stat) throws FileNotFoundException, IOException {
        

        BufferedReader bfr = new BufferedReader(new FileReader(wdb));
        while (true) {
            String inpLin = bfr.readLine();
            if (inpLin == null) {
                bfr.close();
                throw new EOFException("station not found");
            }
            if (inpLin.length() > 10) {
                String[] inpArr = inpLin.substring(0, 10).split(" ");
                if ("#".equals(inpArr[0])) {
//                    System.out.println("inplin " + inpLin);
                    if (stat.equals(inpArr[1])) {
                        PrintWriter pw = new PrintWriter(new File(outDir, stat));
                        pw.println(inpLin);
                        for (int idx = 0; idx < linesToCopy; idx++) {
                            inpLin = bfr.readLine();
                            pw.println(inpLin);
                        }
                        pw.close();
                        bfr.close();
                        break;
                    }
                }
            }
        }
    }

    public static void main(String[] args) {
        try {
            ExtractStationFromWDB esf = new ExtractStationFromWDB(new File(wdbName), outDir, testStat);
//            esf = new ExtractStationFromWDB(new File(wdbName), outDir, "999999");
        } catch (FileNotFoundException ex) {
            LOGGER.fatal("File not found", ex);
        } catch (IOException ex) {
            LOGGER.fatal("IO Error", ex);
        }
    }
}
