/*
Copyright: (C) 2002 Brigham Young University

This program is free software; you can redistribute it and/or modify it
under the terms of the Open Source Software License Agreement for JHDL.

You should have received a copy of the Open Source Software License for
JHDL along with this program.  If you have not, download the License
Agreement at http://www.jhdl.org/license.html or write to:

Brad Hutchings
459 Clyde Bldg
Brigham Young University
Provo, UT 84602


*/


import java.io.File;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.Reader;

import byucc.jhdl.base.HWSystem;
import byucc.jhdl.base.Node;
import byucc.jhdl.base.ProgrammaticTestBench;
import byucc.jhdl.base.Wire;
import byucc.jhdl.Xilinx.XC4000.XC4000TechMapper;
import byucc.jhdl.Logic.Logic;
import byucc.jhdl.Logic.TechMapper;

import byucc.jhdl.examples.des.DES;

/** testbench for DES.  This testbench instantiates encipher and decipher
 * hardware and randomly generates keys and data.  If the output is the same
 * as the input, the circuit works.
 *
 * @author Jeremy Anderson, Anthony Slade */
public class TEST_DES extends Logic implements ProgrammaticTestBench {

  /** Number of cycles to programmatically test the DES circuits */
  public static final int NUM_TEST_CYCLES = 19;

  /** The name of the netlist that represents a good netlist output of
   * the design for this test */
  public static final String GOLD_NETLIST = "GoldNetlist_DESe.edn";

  //main method for simulation from command line
  public static void main(String[] args) {

    boolean gui = false;
    boolean skipNetlistTest = false;

    for ( int ind = 0; ind < args.length; ++ ind ) {
      String arg = args[ind];
      if ( "-v".equals(arg) ) {
	verbose = true;
      } else if ( "-nonetlist".equalsIgnoreCase(arg) ) {
	skipNetlistTest = true;
      } else if ( "-gui".equals(arg) ) {
	gui = true;
      } else {
	showUsage();
	System.exit(1);
      }
    }

    //create HWSystem (parent of the whole system)
    HWSystem hw = new HWSystem();
    //create testbench
    TEST_DES tb = new TEST_DES(hw);

    if ( gui ) {
      new byucc.jhdl.apps.Viewers.cvt.cvtFrame(tb);
    } else {
      // exercise and verify circuit
      tb.execute();
      // perform netlist comparison test
      if ( !skipNetlistTest ) {
	boolean netlistError = false;
	TechMapper tm = Logic.getDefaultTechMapper();
	byucc.jhdl.netlisters.Netlister.setPrintTimestamp(false);
	tm.netlist(tb.my_DESe,"my_DESe.edn");
	byucc.jhdl.netlisters.Netlister.setPrintTimestamp(true);
	Reader fileReaderNew = null;
	Reader fileReaderGold = null;
	try {
	  fileReaderNew = new FileReader("my_DESe.edn");
	  fileReaderGold = new InputStreamReader(tb.getClass().getResourceAsStream(GOLD_NETLIST));
	} catch ( NullPointerException npe ) {
	  System.err.println("Could not perform netlist test of TEST_DES "
			     + "because the golden netlist was not found!");
	  netlistError = true;
	} catch ( IOException ioe ) {
	  ioe.printStackTrace();
	  netlistError = true;
	}
	int diff = byucc.jhdl.util.FileDiff.diff( fileReaderGold,
						  fileReaderNew );
	// dispose the newly created file...
	(new File("my_DESe.edn")).delete();
	if ( 0 != diff || netlistError ) {
	  System.err.println("Netlist diff test for TEST_DES failed!");
	  System.exit(1);
	} else if ( verbose ) {
	  System.out.println("Netlist comparison test for TEST_DES passed.");
	}
      }
    }
  }

  /** Prints out the command line usage for this class */
  public static void showUsage() {
    System.err.println("java byucc.jhdl.examples.des.TEST_DES "
		       + "[-v] [-gui|-noNetlist]");
    System.err.println("\t -v is for verbose");
    System.err.println("\t -gui displays circuit in a graphical viewer");
    System.err.println("\t -noNetlist supresses the netlist test");
  }

  /** testbench constructor */
  public TEST_DES(Node parent) {
    
    //superclass constructor
    super(parent);

    //create wires for inputs and output
    data_in = Logic.wire(this,64,"data_in");
    data_enc = Logic.wire(this,64,"data_enc");
    key_in = Logic.wire(this,64,"key_in");
    data_out = Logic.wire(this,64,"data_out");

    //set Techmapping
    XC4000TechMapper tm = new XC4000TechMapper( true );
    Logic.setDefaultTechMapper(tm);
    Logic.setTechMappingEnabled(true);
    
    //create circuits. static Logic methods are used to "hardwire" the
    //to encipher and decipher
    my_DESe = new DES(this,Logic.constant(this,1,1), // encode constant
		      data_in,key_in,data_enc);
    my_DESd = new DES(this,Logic.constant(this,1,0), // decode constant
		      data_enc,key_in,data_out);
  }

  /** Implementation of the ProgrammaticTestBench interface.  Offers
   * the execution control of the test bench */
  public void execute() {
    for ( int cycle = 0; cycle < NUM_TEST_CYCLES; ++ cycle ) {
      //randomly generate key and data
      dataInValue = (long)(Math.random()*Math.pow(2,63));
      keyValue = (long)(Math.random()*Math.pow(2,63));

      getSystem().cycle(1);

      //get value from output port and print results
      long input = data_in.getL(this);
      long output = data_out.getL(this);
      if ( verbose ) {
	System.out.println("\nCycle = "+cycle+":");
	System.out.println("\tData in ="+Long.toHexString(input));
	System.out.println("\tData out="+Long.toHexString(output));
      }
      if ( input != output ) {
	if ( verbose ) {
	  System.err.println("The input value " + input
			     + " does not equal the output value "
			     + output);
	}
	System.err.println("The DES circuit test failed!");
	System.exit(1);
      } else if ( verbose ) {
	System.out.println("The TEST_DES test passed.");
      }
    }
  }

  /** reset behavior of test bench */
  public void reset() {
    data_in.putL(this,0);
    key_in.putL(this,0);
  }
  
  /** synchronous behavior for test bench */
  public void clock() {
    //put key and data in input ports
    data_in.putL(this,dataInValue);
    key_in.putL(this,keyValue);
  }

  /** The input (non-encrypted) data wire */
  private Wire data_in;
  /** The encryption key input wire */
  private Wire key_in;
  /** The output (after encryption then decryption) wire */
  private Wire data_out;
  /** The intermediate, encrypted data wire */
  private Wire data_enc;

  /** Value to put on the data_in wire on the next clock cycle */
  private long dataInValue;
  /** Value to put on the key_in wire on the next clock cycle */
  private long keyValue;

  /** Controls how loud test output is */
  private static boolean verbose = false;

  /** Encryption DES design */
  private DES my_DESe;
  /** Decryption DES design */
  private DES my_DESd;
}

