/// <summary>
    /// Writes a dfs0 with extraction data for each active intake in every plant. 
    /// Also writes the textfile that can be imported by the well editor.
    /// </summary>
    /// <param name="OutputPath"></param>
    /// <param name="Plants"></param>
    /// <param name="Start"></param>
    /// <param name="End"></param>
    public static void WriteExtractionDFS0(string OutputPath, IEnumerable<PlantViewModel> Plants, DateTime Start, DateTime End)
      {

        //Create the text file to the well editor.
        StreamWriter Sw = new StreamWriter(Path.Combine(OutputPath, "WellEditorImport.txt"), false, Encoding.Default);
        StreamWriter Sw2 = new StreamWriter(Path.Combine(OutputPath, "WellsWithMissingInfo.txt"), false, Encoding.Default);
        StreamWriter Sw3 = new StreamWriter(Path.Combine(OutputPath, "PlantWithoutWells.txt"), false, Encoding.Default);


        var TheIntakes = Plants.Sum(var => var.ActivePumpingIntakes.Count());

        //Create the DFS0 Object
        string dfs0FileName = Path.Combine(OutputPath, "Extraction.dfs0");
        DFS0 _tso = new DFS0(dfs0FileName, TheIntakes);

        DFS0 _tsoStat = new DFS0(Path.Combine(OutputPath, "ExtractionStat.dfs0"), 4);
        Dictionary<int, double> Sum = new Dictionary<int, double>();
        Dictionary<int, double> SumSurfaceWater = new Dictionary<int, double>();
        Dictionary<int, double> SumNotUsed = new Dictionary<int, double>();

        int Pcount = 0;

        int NumberOfYears = End.Year - Start.Year + 1;

        //Dummy year because of mean step accumulated
        _tso.InsertTimeStep( new DateTime(Start.Year, 1, 1, 0, 0, 0));

        for (int i = 0; i < NumberOfYears; i++)
        {
          _tso.InsertTimeStep(new DateTime(Start.Year + i, 12, 31, 12, 0, 0));
          _tsoStat.InsertTimeStep(new DateTime(Start.Year + i, 12, 31, 12, 0, 0));
          Sum.Add(i, 0);
          SumSurfaceWater.Add(i, 0);
          SumNotUsed.Add(i, 0);
        }

        double[] fractions = new double[NumberOfYears];
        int itemCount = 0;

        //loop the plants
        foreach (PlantViewModel P in Plants)
        {
          double val;
          //Add to summed extraction, surface water and not assigned
          for (int i = 0; i < NumberOfYears; i++)
          {
            if (P.plant.SurfaceWaterExtrations.TryGetValue(Start.AddYears(i), out val))
              SumSurfaceWater[i] += val;
            //Create statistics for plants without active intakes
            if (P.ActivePumpingIntakes.Count() == 0)
              if (P.plant.Extractions.TryGetValue(Start.AddYears(i), out val))
                SumNotUsed[i] += val;

            if (P.plant.Extractions.TryGetValue(Start.AddYears(i), out val))
              Sum[i] += val;
          }
          Pcount++;

          //Used for extraction but has missing data
          foreach (var NotUsedWell in P.PumpingIntakes.Where(var => var.Intake.well.UsedForExtraction & (var.Intake.well.HasMissingData() | var.Intake.HasMissingdData())))
          {
            StringBuilder Line = new StringBuilder();
            Line.Append(NotUsedWell.Intake.well.X + "\t");
            Line.Append(NotUsedWell.Intake.well.Y + "\t");
            Line.Append(NotUsedWell.Intake.well.Terrain + "\t");
            Line.Append("0\t");
            Line.Append(P.ID + "\t");
            Sw2.WriteLine(Line);
          }

          //Only go in here if the plant has active intakes
          if (P.ActivePumpingIntakes.Count() > 0)
          {
            //Calculate the fractions based on how many intakes are active for a particular year.
            for (int i = 0; i < NumberOfYears; i++)
            {
              fractions[i] = 1.0 / P.ActivePumpingIntakes.Count(var => (var.StartNullable ?? DateTime.MinValue).Year <= Start.Year + i & (var.EndNullable ?? DateTime.MaxValue).Year >= Start.Year + i);
            }

            //Now loop the intakes
            foreach (var PI in P.ActivePumpingIntakes)
            {
              IIntake I = PI.Intake;
              //Build novanaid
              string NovanaID = P.ID.ToString() + "_" + I.well.ID.Replace(" ", "") + "_" + I.IDNumber;

              _tso.Items[itemCount].ValueType = DataValueType.MeanStepBackward;
              _tso.Items[itemCount].EumItem = eumItem.eumIPumpingRate;
              _tso.Items[itemCount].EumUnit = eumUnit.eumUm3PerYear;
              _tso.Items[itemCount].Name = NovanaID;

              //Loop the years
              for (int i = 0; i < NumberOfYears; i++)
              {
                //Extractions are not necessarily sorted and the time series may have missing data
                var k = P.plant.Extractions.Items.FirstOrDefault(var => var.StartTime.Year == Start.Year + i);

                //If data and the intake is active
                if (k != null & (PI.StartNullable ?? DateTime.MinValue).Year <= Start.Year + i & (PI.EndNullable ?? DateTime.MaxValue).Year >= Start.Year + i)
                  _tso.SetData(i + 1, itemCount + 1, (k.Value * fractions[i]));
                else
                  _tso.SetData(i + 1, itemCount + 1, 0); //Prints 0 if no data available

                //First year should be printed twice
                if (i == 0)
                  _tso.SetData(i, itemCount + 1, _tso.GetData(i + 1, itemCount + 1));
              }

              //Now add line to text file.
              StringBuilder Line = new StringBuilder();
              Line.Append(NovanaID + "\t");
              Line.Append(I.well.X + "\t");
              Line.Append(I.well.Y + "\t");
              Line.Append(I.well.Terrain + "\t");
              Line.Append("0\t");
              Line.Append(P.ID + "\t");
              Line.Append(I.Screens.Max(var => var.TopAsKote) + "\t");
              Line.Append(I.Screens.Min(var => var.BottomAsKote) + "\t");
              Line.Append(1 + "\t");
              Line.Append(Path.GetFileNameWithoutExtension(dfs0FileName) + "\t");
              Line.Append(itemCount+1);
              Sw.WriteLine(Line.ToString());

              itemCount++;
            }
          }
          else //Plants with no wells
          {
            Sw3.WriteLine(P.DisplayName + "\t" + P.ID);
          }
        }


        foreach(var Item in _tsoStat.Items)
        {
          Item.EumItem = eumItem.eumIPumpingRate;
          Item.EumUnit = eumUnit.eumUm3PerSec;
          Item.ValueType = DataValueType.MeanStepBackward;
        }
        
        _tsoStat.Items[0].Name="Sum";
        _tsoStat.Items[1].Name = "Mean";
        _tsoStat.Items[2].Name = "SumNotUsed";
        _tsoStat.Items[3].Name = "SumSurfaceWater";

        for (int i = 0; i < NumberOfYears; i++)
        {
          _tsoStat.SetData(i, 1, Sum[i]);
          _tsoStat.SetData(i, 2, Sum[i]/((double)Pcount));
          _tsoStat.SetData(i, 3, SumNotUsed[i]);
          _tsoStat.SetData(i, 4, SumSurfaceWater[i]);
        }

        _tsoStat.Dispose(); 
        _tso.Dispose();
        Sw.Dispose();
        Sw2.Dispose();
        Sw3.Dispose();
      }
        /// <summary>
    /// Writes a dfs0 with extraction data for each active intake in every plant using the Permits. 
    /// Also writes the textfile that can be imported by the well editor.
    /// </summary>
    /// <param name="OutputPath"></param>
    /// <param name="Plants"></param>
    /// <param name="Start"></param>
    /// <param name="End"></param>
    public static void WriteExtractionDFS0Permits(string OutputPath, IEnumerable<PlantViewModel> Plants, int DistributionYear, int StartYear, int Endyear)
    {

      //Create the text file to the well editor.
      StreamWriter Sw = new StreamWriter(Path.Combine(OutputPath, "WellEditorImportPermits.txt"), false, Encoding.Default);
      StreamWriter Sw2 = new StreamWriter(Path.Combine(OutputPath, "WellsWithMissingInfo.txt"), false, Encoding.Default);
      StreamWriter Sw3 = new StreamWriter(Path.Combine(OutputPath, "PlantWithoutWells.txt"), false, Encoding.Default);

      var TheIntakes = Plants.Sum(var => var.ActivePumpingIntakes.Count());

      //Create the DFS0 Object
      string dfs0FileName = Path.Combine(OutputPath, "ExtractionPermits.dfs0");
      DFS0 _tso = new DFS0(dfs0FileName, TheIntakes);

      int Pcount = 0;

      //Set time
      _tso.InsertTimeStep(new DateTime(StartYear, 1, 1, 0, 0, 0));
      _tso.InsertTimeStep(new DateTime(Endyear, 12, 31, 0, 0, 0));

      double fractions;
      int itemCount = 0;

      //loop the plants
      foreach (PlantViewModel P in Plants)
      {
        Pcount++;

        //Used for extraction but has missing data
        foreach (var NotUsedWell in P.PumpingIntakes.Where(var => var.Intake.well.UsedForExtraction & (var.Intake.well.HasMissingData() | var.Intake.HasMissingdData())))
        {
          StringBuilder Line = new StringBuilder();
          Line.Append(NotUsedWell.Intake.well.ID + "\t");
          Line.Append(NotUsedWell.Intake.well.X + "\t");
          Line.Append(NotUsedWell.Intake.well.Y + "\t");
          Line.Append(NotUsedWell.Intake.well.Terrain + "\t");
          Line.Append("0\t");
          Line.Append(P.ID);
          Sw2.WriteLine(Line);
        }

        //Only go in here if the plant has active intakes
        if (P.ActivePumpingIntakes.Count() > 0)
        {
          //Calculate the fractions based on how many intakes are active for a particular year.
          fractions = 1.0 / P.ActivePumpingIntakes.Count(var => (var.StartNullable ?? DateTime.MinValue).Year <= DistributionYear & (var.EndNullable ?? DateTime.MaxValue).Year >= DistributionYear);

          //Now loop the intakes
          foreach (var PI in P.ActivePumpingIntakes.Where(var => (var.StartNullable ?? DateTime.MinValue).Year <= DistributionYear & (var.EndNullable ?? DateTime.MaxValue).Year >= DistributionYear))
          {
            IIntake I = PI.Intake;
            //Build novanaid
            string NovanaID = P.ID.ToString() + "_" + I.well.ID.Replace(" ", "") + "_" + I.IDNumber;

            _tso.Items[itemCount].ValueType = DataValueType.MeanStepBackward;
            _tso.Items[itemCount].EumItem = eumItem.eumIPumpingRate;
            _tso.Items[itemCount].EumUnit = eumUnit.eumUm3PerYear;
            _tso.Items[itemCount].Name = NovanaID;


            //If data and the intake is active
            _tso.SetData(0, itemCount + 1, (P.Permit * fractions));
            _tso.SetData(1, itemCount + 1, (P.Permit * fractions));


            //Now add line to text file.
            StringBuilder Line = new StringBuilder();
            Line.Append(NovanaID + "\t");
            Line.Append(I.well.X + "\t");
            Line.Append(I.well.Y + "\t");
            Line.Append(I.well.Terrain + "\t");
            Line.Append("0\t");
            Line.Append(P.ID + "\t");
            Line.Append(I.Screens.Max(var => var.TopAsKote) + "\t");
            Line.Append(I.Screens.Min(var => var.BottomAsKote) + "\t");
            Line.Append(1 + "\t");
            Line.Append(Path.GetFileNameWithoutExtension(dfs0FileName) + "\t");
            Line.Append(itemCount+1);
            Sw.WriteLine(Line.ToString());

            itemCount++;
          }
        }
        else //Plants with no wells
        {
          Sw3.WriteLine(P.DisplayName + "\t" + P.ID);
        }
      }
      _tso.Dispose();
      Sw.Dispose();
      Sw2.Dispose();
      Sw3.Dispose();
    }
    private void MakePlots()
    {
      if (!PlotsMade) //Only do this once
      {

        Model mShe = new Model(SheFileName);
        DFS3 dfs = new DFS3(Dfs3FileName);
        Item dfsI = dfs.Items[ItemNumber - 1];

        List<TimestampSeries> well_Concentration = new List<TimestampSeries>();

        int[] TimeSteps = ParseString(TimeStepsAsString, 0, dfs.NumberOfTimeSteps - 1);
        int[] WellNumbers = ParseString(WellsAsString, 0, mShe.ExtractionWells.Count - 1);

        List<MikeSheWell> wells = new List<MikeSheWell>();
        foreach (int j in WellNumbers)
          wells.Add(mShe.ExtractionWells[j]);

        foreach (int i in TimeSteps)
        {
          int k = 0;
          foreach (var w in wells)
          {
            if (i == TimeSteps[0])
              well_Concentration.Add(new TimestampSeries(w.ID, new Unit(dfsI.EumQuantity.UnitAbbreviation, 1, 0)));
            well_Concentration[k].Items.Add(new TimestampValue(dfs.TimeSteps[i], (dfs.GetData(i, ItemNumber)[w.Row, w.Column, w.Layer])));
            k++;
          }
        }

        //Sets the upper title
        Header.Content = dfsI.Name;

        //Sets the title of the y-axis
        var ytitle = new VerticalAxisTitle();
        ytitle.Content = dfsI.EumQuantity.ItemDescription + " [" + dfsI.EumQuantity.UnitAbbreviation + "]";
        TheChart.Children.Add(ytitle);

        int l = 0;
        //Loop the wells for plotting
        foreach (var w in wells)
        {
          if (g != null)
          {
            TheChart.Children.Remove(g);
            TheChart.FitToView();
          }

          var axis = new Microsoft.Research.DynamicDataDisplay.Charts.HorizontalDateTimeAxis();
          TheChart.MainHorizontalAxis = axis;
          TheChart.MainVerticalAxis = new Microsoft.Research.DynamicDataDisplay.Charts.VerticalAxis();
          //set the data source
          EnumerableDataSource<TimestampValue> ds = new EnumerableDataSource<TimestampValue>(well_Concentration[l].Items);
          ds.SetXMapping(var => axis.ConvertToDouble(var.Time));
          ds.SetYMapping(var => var.Value);
          //create the graph
          g = TheChart.AddLineGraph(ds, new Pen(Brushes.Black, 3), new PenDescription(w.ID));
         //create a filename
          outfile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Dfs3FileName), "Well_No" + "_" + WellNumbers[l].ToString() + "_" + dfsI.EumQuantity.ItemDescription);
          //now save to file          
          this.UpdateLayout();

          MainWindow.SaveScreen(this, outfile + ".jpg", (int)ActualWidth, (int)ActualHeight);


          //Now create the dfs0-file
          using (DFS0 dfs0 = new DFS0(outfile + ".dfs0", 1))
          {
            dfs0.FirstItem.Name = dfsI.Name;
            dfs0.FirstItem.EumItem = dfsI.EumItem;
            dfs0.FirstItem.EumUnit = dfsI.EumUnit;
            dfs0.FirstItem.ValueType = dfsI.ValueType;

            int t = 0;
            foreach (var v in well_Concentration[l].Items)
            {
              dfs0.InsertTimeStep(v.Time);
              dfs0.SetData(t, 1, v.Value);
              t++;
            }
          }

          //Now create the text-file
          using (StreamWriter sw = new StreamWriter(outfile + ".txt", false))
          {
            foreach (var v in well_Concentration[l].Items)
            {
              sw.WriteLine(v.Time + "; " + v.Value);
            }
          }
          l++;
        }
        mShe.Dispose();
        dfs.Dispose();
        PlotsMade = true;
      }
    }