package genesom;

/*
 *
 *   Load recursively dumped neurons.
 *
 *
 */

import java.io.Writer;
import java.io.BufferedWriter;
import java.io.Reader;
import java.io.LineNumberReader;
import java.util.Vector;


public class PersistentMap
  extends Map
{

  public PersistentMap() { }


  public PersistentMap(Reader reader) {

    Vector nodesv = new Vector();

    LineNumberReader in = new LineNumberReader(reader);

    int nonode = 0;

    String line = null;

    try {

      while( (line = in.readLine()) != null ) {

        if(!(line = line.trim()).startsWith(InputPatterns.DEFAULT_COMMENT_INDICATOR))
          nodesv.add(new Node(line));
      }
    }
    catch(Exception nse) {
      nse.printStackTrace();
      throw new RuntimeException(nse + "::: Unexpected value in line " + in.getLineNumber() + " : " + line);
    }

    int len = nodesv.size();

    nodes = new Node[len];

    for(int i = 0; i < len; i++) {
      Node n = (Node)nodesv.elementAt(i);
      nodes[n.init_id] = n;
    }


    // replace neuron stubs by real references
    //
    for(int i = 0; i < len; i++) {

      Node n = nodes[i], nn[] = n.getNeighbours();

      for(int k = 0; k < nn.length; k++)
        nn[k] = nodes[nn[k].getInitID()];

      GridPosition cntx = n.context();

      cntx.n1 = nodes[cntx.n1.getInitID()];
      cntx.n2 = nodes[cntx.n2.getInitID()];
      cntx.n3 = nodes[cntx.n3.getInitID()];
    }

    for(int i = 0; i < len; i++)
      nodes[i].id = nodes[i].init_id;

//    for(int i = 0; i < len; i++)
//      System.err.println(nodes[i].toPersistentRepresentation());

    Node.sid = len - 1;
  }


  public static void nodesPersistence(Node[] nodes, Writer writer) {

    BufferedWriter out = new BufferedWriter(writer);

    for(int i = 0; i < nodes.length; i++) {
      try {
        if(nodes[i] != null) {
          out.write(nodes[i].toPersistentRepresentation());
          out.newLine();
        }
      }
      catch(java.io.IOException ioe) {
        throw new RuntimeException("A write error occured @ node " + i);
      }
    }
    try { out.flush(); }
    catch(Exception e) {}
  }

  public void createNodes() {

  }

}




