import java.io.*;
import java.util.*;

/** 
 *  Demo program showing how to read data from a text file 
 *  and write it to a binary file
 *
 *  @author Nick Howe
 *  @version 9 April 2013
 */
public class ConvertTextToBinary {
    /** Reading in from a text file */
    private static LinkedList<Employee> readDataFromTextFile(String fileName) {
        LinkedList<Employee> employees = new LinkedList<Employee>();

        // encase all output in try/catch in case of error
        try {
            BufferedReader in = new BufferedReader(new FileReader(fileName));
            String line = in.readLine();
            while (line != null) {
                int dollar = line.indexOf("$");
                String name = line.substring(0,dollar-1);
                double salary = Double.valueOf(line.substring(dollar+1));
                //System.out.println(name+" $"+salary);
                employees.add(new Employee(name,salary));
                line = in.readLine();
            }
        } catch (IOException e) {
            System.err.println("Problem reading from file.");
        }
        return employees;
    }

    /** Writing to a binary file */
    public static void writeDataToBinaryFile(String fileName, 
                                             LinkedList<Employee> employees) {
        // encase all output in try/catch in case of error
        try {
            // Open a file and create a PrintWriter to it
            DataOutputStream out = new DataOutputStream(new FileOutputStream(fileName));
            
            // loop through employees and print a line for each
            for (Employee e: employees) {
                out.writeUTF(e.getName());
                out.writeDouble(e.getSalary());
            }
            
            // file contents aren't written until file is closed
            out.close();
        } catch (IOException e) {
            System.err.println("Problem writing to file.");
        }
    }

    /** The main method calls others to read data in and out */
    public static void main(String[] args) {
        LinkedList<Employee> employees = null;
        try {
            // read in
            employees = readDataFromTextFile(args[0]);

            // write out
            writeDataToBinaryFile(args[1],employees);

        } catch (ArrayIndexOutOfBoundsException e) {
            System.err.println("Usage:  java ConvertTextToBinary employees.txt employees.bin");
        }
    }
}
