#include <malloc.h>
#include <stdio.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <sys/types.h>
#include <time.h>
#include "delay.h"

#ifndef CLOCKS_PER_SEC
#define CLOCKS_PER_SEC 1000000
#endif

int main()
{
  int Choice = 0;
  char Filename[255];
  double cstart, cend;

  while (1)
  {
    printf("\n\n");
    printf("1. Load RC tree from file\n");
    printf("2. Perform timing analysis\n");
    printf("3. Exit\n");
    printf("Choice: ");

    /* Check for a valid input. */
    if (!scanf("%d", &Choice))
      {
	/* scanf didn't give anything back? The user probably gave us something
	   unreadable. Ignore everything up to a newline */
	while ('\n' != getchar()) ;
	Choice = 0;
      }

    switch (Choice)
    {
      case 1:
        printf("\nFilename: ");
        scanf("%254s", Filename);

	/* Check to make sure the tree is cleared */
	if (NULL != G_Tree_Ptr)
	  {
	    printf("Deleting old tree...\n");
	    free(G_Tree_Ptr); G_Tree_Ptr = NULL;
	    G_Root_Ptr = NULL; // just to be safe
	  }

	FILE * Input_File = fopen(Filename,"r");
	if ( NULL == Input_File )
	  {
	    printf("ERROR: File %s could not be opened!\n",
		   Filename);
	    break;
	  }

        //Elapsed time action
        cstart = (double) clock();
	/* Load the actual tree in */
	RC_Load(Input_File);
        cend = (double) clock();
	if (NULL == G_Tree_Ptr)
	  {
	    printf("ERROR: Load failed!\n");
	    break;
	  }
	fclose(Input_File);

        printf("\nResistance per unit length (ohm/um): %lg\n",
	       G_Resistance_Per_Length);
        printf("Capacitance per unit length (F/um): %lg\n",
	       G_Capacitance_Per_Length);
        printf("Sink node capacitance (F): %lg\n",
	       G_Sink_Node_Capacitance);
        printf("Buffer output resistance (ohm): %lg\n",
	       G_Buffer_Output_Resistance);
        printf("Sinkcount: %d\n", G_Sinkcount);
        printf("Nodecount: %d\n", G_Nodecount);
        printf("\nElapsed time: %lg\n", (cend - cstart)/CLOCKS_PER_SEC);
        break;
      case 2:
        //perform timing analysis
	if (NULL == G_Tree_Ptr)
	  {
	    printf("ERROR: No tree loaded!\n");
	    break;
	  }

        // Elapsed time action
        cstart = (double) clock();
	RC_Timing();
        cend = (double) clock();
        printf("\nElapsed time: %lg\n", (cend - cstart)/CLOCKS_PER_SEC);
        break;
      case 3:
	/* Clean up */
	if (G_Tree_Ptr)
	  {
	    free(G_Tree_Ptr);
	  }
        return 0;
    default:      
      printf("Invalid option!\n");
    }
  }

  return 0;
}
