/* ---------------------------------------------------------------
 File:                           FileWriter.java
 Package:                        FSM Analyzer 1.0
 Author:                         Dr. Ratnesh Kumar and Bharath Oruganti
 V1.0 10/02/97.
 Initial Developers:             Magda & Octavian Procopiuc
 ---------------------------------------------------------------*/
 
/*
 * Dr. Ratnesh Kumar, Bharath S. Oruganti.
 * Electrical Engineering Department.
 * University of Kentucky.
 * October, 1997.
 *
 * Copyright (c) 1997
 * All rights reserved.
 */

package flap;


import java.util.*;
import java.io.*;

/**
 * This class is used to write a given machine in a given
 * file.
 */
public class FileWriter {

    public Machine	a;

    public FileWriter(Machine a) {
        this.a = a;
    }

    /**
     * Tries to write the machine in the specified file.
     */
    public void write(String fileName) throws Exception {
        FileOutputStream	out = null;

        out = new FileOutputStream(fileName);
        PrintStream ps = new PrintStream(out);   
    
        if (a.d.theStates.size() > 0) {
            ps.println(a.d.theStates.size());
            ps.println();

            State s1 = a.d.initialState;

            if (s1 == null) {
                throw new Exception(
                        "Failure in writing a machine state without initial state!");
            }
            ps.println(transitionsFrom(s1));
            for (Enumeration e = a.d.theStates.elements(); e.hasMoreElements();) {
                State s2 = (State) e.nextElement();

                if (s2 != s1) {
                    ps.println(transitionsFrom(s2));
                }
            }
        } else {
            throw new Exception(
                    "Failure in writing a machine state with zero state!");
        }

        ps.close();
    }	// end of method write.

    /* returns the string describing state s (argument) and transition starting from s.
     * the returned string follows the file format (see user manual) and is used to
     * write to file when saving a state machine from the graphic to file.
     */
    private String transitionsFrom(State s) {

        String	answer = "";
        Transition	t;
        int i;

        a.d.setTransitions(s, false);
        if (s.isFinal) {
            i = 1;
        } else {
            i = 0;
        }
        answer = "\n" + s.label + "\t" + i + "\t" + s.transitions.size() + "\n";
        for (Enumeration e = s.transitions.elements(); e.hasMoreElements();) {
            t = (Transition) e.nextElement();
                answer += ((t.label.trim().equals("")) ? "*" : t.label.trim())
                        + "\t" + t.to.label + "\n";

        }
        return answer;
    }	// end of method transitionsFrom.

}	// end of class FileWriter.
