public void goToPreviousEvent()
    {
        GUI_Main comp = this.GetComponent <GUI_Main>() as GUI_Main;

        Evvent   PreviousEvent = StoryLine[0];
        double   DeltaSmallest = double.MaxValue;
        DateTime currentDate   = this.currentClosestEvent.Date;

        foreach (Evvent currentEvent in StoryLine)
        {
            if (currentEvent != this.currentClosestEvent)
            {
                if ((this.SelectedTome == this.TheDatabase.TomeDict["ASOIAF"]) || (currentEvent.Book == this.SelectedTome))
                {                       //We consider only evvents for selected Tome!
                    if (currentEvent.Date < currentDate)
                    {
                        double delta = (currentEvent.Date - currentDate).TotalSeconds;
                        if (delta < 0)
                        {
                            delta *= -1;
                        }

                        if (delta < DeltaSmallest)
                        {
                            DeltaSmallest = delta;
                            PreviousEvent = currentEvent;
                        }
                    }
                }
            }
        }
        this.currentClosestEvent = PreviousEvent;
        comp.ScrollValueREAL     = convertDateToRatio(this.currentClosestEvent.Date);
    }
    public Evvent getCurrentEvent()
    {
        Evvent ClosestEvent  = StoryLine[0];
        double DeltaSmallest = double.MaxValue;

        double currentLocalRatio = this.GetComponent <GUI_Main>().ScrollValueREAL;

        //Debug.Log (currentLocalRatio);

        System.DateTime TimeSliderAsDate = convertRatioToDate(currentLocalRatio);
        //Debug.Log (TimeSliderAsDate);
        foreach (Evvent currentEvent in StoryLine)
        {
            TimeSpan delta = currentEvent.Date - TimeSliderAsDate;             //Warning delta.TotalSeconds is SIGNED
            //Debug.Log (delta.TotalSeconds);

            double deltaAsDuration = delta.TotalSeconds;
            if (deltaAsDuration < 0)
            {
                deltaAsDuration *= -1;
            }

            //Debug.Log (deltaAsDuration);

            if (deltaAsDuration < DeltaSmallest)
            {
                DeltaSmallest = deltaAsDuration;
                ClosestEvent  = currentEvent;

                //Debug.Log ("HERE");
            }
        }

        return(ClosestEvent);
    }
    void Update()
    {
        GUI_Main comp = this.GetComponent <GUI_Main>() as GUI_Main;

        //Debug.Log (comp.ScrollValue);

        if (this.SelectedTome == this.TheDatabase.TomeDict["ASOIAF"])
        {
            updateCharacters(comp.ScrollValueREAL);
            //this.currentDate = convertRatioToDate(comp.ScrollValue);
            this.currentClosestEvent = this.getCurrentEvent();
        }
        else
        {
            double LocalTimeRatio = comp.ScrollValueREAL;

            // ScrollValue means the ratio for current selected TOme,
            // so we have to convert it to a maximum update
            DateTime TheDate = convertRatioToDate(comp.ScrollValueREAL);

            //float GlobalTimeRAtio = convertDateToRatio(TheDate);

            Tome   MasterTome      = this.TheDatabase.TomeDict["ASOIAF"];      //TODO: create a method that returns the MasterTome.
            int    DateNumbers     = (TheDate - MasterTome.Start).Days;
            int    TotalNumbers    = (MasterTome.End - MasterTome.Start).Days;
            double GlobalTimeRAtio = (DateNumbers / (double)TotalNumbers);

            updateCharacters(GlobalTimeRAtio);
            //this.currentDate = TheDate;
            this.currentClosestEvent = this.getCurrentEvent();
        }


        //Debug.Log ("Closest is ="+this.currentClosestEvent.Name );
    }
    public void goToNextEvent()
    //public Evvent getNextEvent()
    {
        GUI_Main comp = this.GetComponent <GUI_Main>() as GUI_Main;

        //Debug.Log ("current Event found is "+currentClosestEvent.Name+" @="+comp.ScrollValueREAL+" "+currentClosestEvent.Date.ToString("dd MMM HH:mm:ss"));

        Evvent   NextEvent     = StoryLine[0];
        double   DeltaSmallest = double.MaxValue;
        DateTime currentDate   = this.currentClosestEvent.Date;

        foreach (Evvent currentEvent in StoryLine)
        {
            if (currentEvent != this.currentClosestEvent)
            {
                if ((this.SelectedTome == this.TheDatabase.TomeDict["ASOIAF"]) || (currentEvent.Book == this.SelectedTome))
                {                       //We consider only evvents for selected Tome!
                    if (currentEvent.Date > currentDate)
                    {
                        double delta = (currentEvent.Date - currentDate).TotalSeconds;
                        if (delta < 0)
                        {
                            delta *= -1;
                        }

                        if (delta < DeltaSmallest)
                        {
                            DeltaSmallest = delta;

                            NextEvent = currentEvent;
                        }
                    }
                }
            }
        }

        this.currentClosestEvent = NextEvent;

        comp.ScrollValueREAL = convertDateToRatio(this.currentClosestEvent.Date);

        //Debug.Log ("Next Event found is "+NextEvent.Name+" @="+comp.ScrollValueREAL+" "+NextEvent.Date.ToString("dd MMM HH:mm:ss"));
        //Debug.Log ("=====================");
    }
    void Start()
    {
        this.TheDatabase = CLS_Database.Instance;

        this.CharacterDict   = new Dictionary <string, GameObject>();
        this.CharacterMotion = new Dictionary <string, List <Evvent> >();
        this.CharacterPath   = new Dictionary <GameObject, LineRenderer>();

        this.StoryLine = new List <Evvent>();

        //Deactivate Kernel MainMenu (and read player options)
        GameObject   Kernel     = GameObject.FindGameObjectWithTag("Core");
        GUI_MainMenu KernelComp = Kernel.GetComponent <GUI_MainMenu>();


        this.SelectedTome = this.TheDatabase.TomeDict[KernelComp.SelectedTome];
        Kernel.SetActive(false);

        //Start to read StoryDatabase.
        string[] LineBuffer = DatabaseDumpFile.text.Split('\n');
        //Debug.Log ("Read "+LineBuffer.Length+" lines from "+DatabaseDumpFile.name);

        foreach (string currentLine in LineBuffer)
        {
            if (currentLine.Contains("\t"))
            {
                string[] TokkenizedLine = currentLine.Split('\t');
                if (TokkenizedLine[8].Length > 0)                       //We consider only the lines with Characters defined in it.
                {
                    //Debug.Log (currentLine);

                    int Year;
                    int.TryParse(TokkenizedLine[0], out Year);

                    int Month, Day;
                    int.TryParse(TokkenizedLine[1].Split('/')[0], out Month);
                    int.TryParse(TokkenizedLine[1].Split('/')[1], out Day);

                    string EventName = TokkenizedLine[2];

                    string ChapterCode      = TokkenizedLine[3];
                    string ChapterCharacter = TokkenizedLine[4];
                    string BookCode         = TokkenizedLine[5];
                    int    Chapter;
                    int.TryParse(TokkenizedLine[6], out Chapter);

                    string Citation = TokkenizedLine[7];

                    string[] Characters = TokkenizedLine[8].Trim().Split(',');

                    string Location = TokkenizedLine[9];

                    //To make each evvent with an unique date (avoid later bugs) let's give it a random time:
                    int rHour    = UnityEngine.Random.Range(0, 24);
                    int rMinute  = UnityEngine.Random.Range(0, 60);
                    int rSeconds = UnityEngine.Random.Range(0, 60);

                    Evvent newEvent = new Evvent();
                    newEvent.Date = new System.DateTime(Year, Month, Day, rHour, rMinute, rSeconds);
                    newEvent.Name = EventName;

                    if (BookCode != "")
                    {
                        if (BookCode != "TWOW")
                        {
                            newEvent.Book = this.TheDatabase.TomeDict[BookCode];
                        }
                    }


                    newEvent.Characters = new List <GameObject>();
                    foreach (string currentCharacterName in Characters)
                    {
                        string currentCharacterName2 = currentCharacterName.Trim();
                        //currentCharacterName = currentCharacterName.Trim();
                        if (this.CharacterDict.ContainsKey(currentCharacterName2))
                        {
                            //Debug.LogWarning ("this.CharacterDict["+currentCharacterName+"]="+this.CharacterDict[currentCharacterName].name);
                        }
                        else
                        {
                            //Debug.Log (currentCharacterName+" is NOT in the Dict!!!");
                            this.createCharacterPawn(currentCharacterName2);
                        }
                        newEvent.Characters.Add(this.CharacterDict[currentCharacterName2]);

                        if (!CharacterMotion.ContainsKey(currentCharacterName2))
                        {
                            CharacterMotion[currentCharacterName2] = new List <Evvent>();
                        }
                        CharacterMotion[currentCharacterName2].Add(newEvent);
                    }

                    newEvent.Location = GameObject.Find(Location);
                    if (newEvent.Location == null)
                    {
                        Debug.LogError("ERROR, no location found for =" + Location);
                    }
                    //Debug.Log (newEvent.Location.name);

                    //Now we have to set the HappeningTime:
                    //newEvent.HappeningTime = this.SelectedTome.getRatio(newEvent.Date);
                    newEvent.HappeningTime = this.TheDatabase.TomeDict["ASOIAF"].getRatio(newEvent.Date);

                    newEvent.Info = Citation;

                    StoryLine.Add(newEvent);
                }

                //Now we have to add a starting point for every characters:
                //foreach(string CharacterName in this.CharacterMotion.Keys)
                //{
                //	this.CharacterMotion[0.0f] = Vector3.zero;
                //}
            }
        }

        //initForTome();

        createMotionPaths();

        #region StoryLineDebugging
        string LoggedBuffer = "";
        foreach (KeyValuePair <string, List <Evvent> > kvp in this.CharacterMotion)
        {
            //Debug.Log ("CharacterName="+kvp.Key);
            //Tome currentBook=null;
            LoggedBuffer += "\nCharacter: " + kvp.Key;
            foreach (Evvent ev in kvp.Value)
            {
                /*
                 * if(ev.Book!=null)
                 * {
                 *      if(ev.Book!=currentBook)
                 *      {
                 *              currentBook = ev.Book;
                 *              LoggedBuffer+="\n\t"+ ev.Book.CodeName;
                 *      }
                 * }
                 */
                int percent = Mathf.RoundToInt(ev.HappeningTime * 100f);
                //Debug.Log ("\t     "+ percent+"% => "+ ev.Location.name+" ("+ev.Name+")");


                LoggedBuffer += "\n\t" + ev.Date.ToString("d/MM/yyy") + " (" + percent + "%) => " + ev.Location.name + " (" + ev.Name + ")";
            }
        }
        //Debug.LogWarning(LoggedBuffer);
        #endregion
    }
    void drawCalendar()
    {                                             //Draw the whole saga outside of the bounds/
        float ATOM_WIDTH = Screen.width * 0.2f;   //smallest bucket is the day.

        float ATOM_HEIGHT = Screen.height * 0.1f; //std line

        int currentMonth = 0;
        int currentYear  = 0;

        MAX_LENGTH = 0f;

        float SmallestDeltaFromScreen = float.MaxValue;

        //centralEvent = StorylineComponent.getCurrentEvent();

        currentCursorIt = this.baseCursor;

        foreach (Evvent currentEvent in StorylineComponent.StoryLine)           //Be carefull, The list must be ordered chronologically...
        {
            System.DateTime currentEventDate = currentEvent.Date;

            #region YEAR_LINE
            //Do we have change year ?
            if (currentEventDate.Year != currentYear)
            {
                int cnt = countEventsForYear(currentEventDate.Year);
                if (GUI.Button(new Rect(currentCursorIt, ATOM_HEIGHT, cnt * ATOM_WIDTH, ATOM_HEIGHT), currentEventDate.Year.ToString()))
                {
                    Debug.Log(currentEventDate.Year.ToString());
                }
                currentYear = currentEventDate.Year;
                MAX_LENGTH += cnt * ATOM_WIDTH;
            }
            #endregion

            #region MONTH_LINE
            //Do we have change month ?
            if (currentEventDate.Month != currentMonth)
            {
                int cnt = countEventsForMonth(currentEventDate.Month, currentEventDate.Year);
                GUI.Button(new Rect(currentCursorIt, ATOM_HEIGHT * 2, cnt * ATOM_WIDTH, ATOM_HEIGHT), currentEventDate.ToString("MMMM"));
                currentMonth = currentEventDate.Month;
            }
            #endregion

            if (GUI.Button(new Rect(currentCursorIt, ATOM_HEIGHT * 3, ATOM_WIDTH, ATOM_HEIGHT), currentEventDate.Day.ToString()))
            {
                //this.StorylineComponent.currentClosestEvent = currentEvent;
                //this.GetComponent<GUI_Main>().ScrollValueREAL = this.GetComponent<BHV_Storyline>().convertDateToRatio( currentEvent.Date );	//UGLIER: you die.
                //centralEvent = currentEvent;
            }

            this.EventToCursorDict[currentEvent] = currentCursorIt;             //storing the offset from base

            currentCursorIt += ATOM_WIDTH;


            //calculate delta
            if ((Mathf.Abs(Screen.width * 0.5f - currentCursorIt)) < SmallestDeltaFromScreen)
            {
                SmallestDeltaFromScreen = Mathf.Abs(Screen.width * 0.5f - currentCursorIt);
                centralEvent            = currentEvent;
            }
        }

        //Debug.Log ("Central Event is ="+centralEvent.Date.Day+"/"+centralEvent.Date.Month+"/"+centralEvent.Date.Year);
        //System.TimeSpan delta = centralEvent.Date - StorylineComponent.currentDate;
        //TimeSpan currentDateAsDuration = StorylineComponent.currentDate - StorylineComponent.SelectedTome.Start;
        //TimeSpan centralEventDateAsDuration = centralEvent.Date - StorylineComponent.SelectedTome.Start;
        //float ratio = (currentDateAsDuration.Days+1) / (float)centralEventDateAsDuration.Days;

        //Debug.Log ( StorylineComponent.SelectedTome.Start );

        //Debug.Log (currentDateAsDuration.Days);
        //Debug.Log (centralEventDateAsDuration.Days);
        //Debug.Log (ratio);
        //currentCursor *= ratio;
    }