using System;
using System.Collections.Generic;
using System.Text;

using Spherical;
using Spherical.IO;

namespace MaskXYZ
{
    class Program
    {
        static void Usage(string msg)
        {
            Console.Error.WriteLine("Usage: MaskXYZ.exe mask1.bin [mask2.bin...] < in.xyz > out.xyz");
            if (msg != null || msg != "")
                Console.Error.WriteLine("Error: {0}", msg);
        }

        static int Main(string[] args)
        {
            if (args.Length < 1)
            {
                Usage("No mask file given!");
                return 1;
            }

            Region mask = new Region(1000);
            foreach (string maskfile in args)
            {
                Console.Error.Write(" - Loading masks from '{0}'... ", maskfile); 
                Console.Error.Flush();
                BinReader rdr = new BinReader(maskfile);
                Region m = rdr.ReadRegion();
                m.Simplify(false, Const.Tolerance, Const.MaximumIteration, false);
                mask.Union(m);
                rdr.Close();
                Console.Error.WriteLine("done.");
            }
            //mask.Sort(Convex.ComparisonAreaDescending);

            Console.Error.WriteLine(" - Filtering input...");
            int counterAll = 0, counterIn = 0;
            char[] sep = new char[] {' ', '\t', ','};
            string line;
            while ((line = Console.In.ReadLine()) != null)
            {
                counterAll++;
                string[] tok = line.Split(sep, StringSplitOptions.RemoveEmptyEntries);
                try
                {
                    double x = double.Parse(tok[0].Trim(sep));
                    double y = double.Parse(tok[1].Trim(sep));
                    double z = double.Parse(tok[2].Trim(sep));
                    Cartesian p = new Cartesian(x, y, z, true);

                    if (!mask.SmartCovers(p, 0))
                    {
                        counterIn++;
                        Console.Out.WriteLine(line);
                    }
                }
                catch (FormatException fmtex)
                {
                    Console.Error.WriteLine("ERROR PARSING LINE:\n{0}", line);
                    throw fmtex;
                }
            }
            Console.Error.WriteLine(" - Output: {0} out of {1}", counterIn, counterAll);

            return 0;
        }
    }
}
