﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace GLPSOL_stdin
{
    static class Program
    {
        public static void Main(string[] args)
        {
            string modelPath = @"E:\gusek\examples\money.mod";
            Stream stream = GLPSOLStreamOut(modelPath);
            string outputFilePath = CBCStreamIn(stream);
        }

        private static Stream GLPSOLStreamOut(string modelPath)
        {
            string glpsolPath = @"E:\gusek\glpsol.exe";
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.FileName = glpsolPath;

            process.StartInfo.Arguments = String.Format("--math {0} --wlp /dev/stdout --check", modelPath);
            process.StartInfo.RedirectStandardOutput = true;
            process.Start();
            string sOutPut;
            do
            {
                sOutPut = process.StandardOutput.ReadLine();
            }
            while (!sOutPut.Contains("Writing problem data"));


            StringBuilder sb = new StringBuilder();
            string wlpOutput;
            do
            {
                wlpOutput = process.StandardOutput.ReadLine();
                sb.AppendLine(wlpOutput);
            }
            while (wlpOutput != "End");

            return new MemoryStream(Encoding.ASCII.GetBytes(sb.ToString()));
        }

        private static string CBCStreamIn(Stream inputModel)
        {
            string cbcPath = @"E:\Cbc-2.7.8\Cbc\MSVisualStudio\v10\Win32\Debug\cbc.exe";
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.FileName = cbcPath;

            string outputStreamPath = @"E:\temp\shiftcover_lp_stream.out";
            process.StartInfo.Arguments = String.Format("-import stdin_lp -solve -solution {0}", outputStreamPath);
            process.StartInfo.RedirectStandardInput = true;
            process.Start();
            StreamReader tr = new StreamReader(inputModel);
            process.StandardInput.Write((tr.ReadToEnd()));
            return outputStreamPath;
        }
    }
}
