using System;
using System.Data;
using System.Data.Odbc;
using System.IO;
using System.Text;

namespace Axls2csv {
	class Class1 {
		[STAThread]
		static void Main(string[] args) {
			if (args.Length < 3) {
				Console.Error.WriteLine("Axls2csv <input.xls> <Descriptor1$> <output.csv>");
				Environment.Exit(1);
			}
			using (OdbcConnection db = new OdbcConnection("Driver={Microsoft Excel Driver (*.xls)};ReadOnly=1;DBQ=" + args[0] + ";")) {
				db.Open();
				OdbcCommand cmd = new OdbcCommand("SELECT * FROM [" + args[1] + "]", db);
				OdbcDataReader dr = cmd.ExecuteReader();
				using (StreamWriter wr = new StreamWriter(args[2], false, Encoding.Default)) {
					while (dr.Read()) {
						int cx = dr.FieldCount;
						for (int x=0; x<cx; x++) {
							if (x != 0)
								wr.Write(",");
							wr.Write(Ut.Escape(dr[x]));
						}
						wr.WriteLine();
					}
				}
				db.Close();
				Console.WriteLine("Ok");
			}
		}

		class Ut {
			static char[] Marks { get { return "\r\n,\"".ToCharArray(); } }

			public static string Escape(object o) {
				return Escape((o == null || o is DBNull) ? "" : o.ToString());
			}
			public static string Escape(string s) {
				if (s.IndexOfAny(Marks) < 0) {
					return s;
				}
				return "\"" + s.Replace("\"", "\"\"") + "\"";
			}
		}
	}
}
