text:
#include <libv/geometry/pose.hpp>
#include <libv/geometry/rotation.hpp>
#include <libv/geometry/camera_model.hpp>

#include <libv/graphic/viewer_context.hpp>
#include <GL/gl.h>
#include <boost/bind/bind.hpp>
#include <boost/function.hpp>
#include <depends/aligned_vector.hpp>

#include <iostream>

#include <libv/lma/lma.hpp>

namespace lma
{
  template<> struct Size<v::Pose> { enum {value = 6}; };
  template<> struct Size<v::UnifiedCameraModel> { enum {value = 5}; };

  template<int I> void apply_small_increment(Eigen::Matrix3d& rotation, double d, v::numeric_tag<I>, const Adl&)
  {
    v::apply_small_rotation(rotation,Eigen::Vector3d(I==0?d:0.0,I==1?d:0.0,I==2?d:0.0));
  }

  template<int I> void apply_small_increment(v::Pose& o, double d, v::numeric_tag<I>, const Adl&)
  {
    if (I<3)
      o.translation()[I] += d;
    else
      v::apply_small_rotation(o.rotation(),Eigen::Vector3d(I==3?d:0.0,I==4?d:0.0,I==5?d:0.0));
  }

  inline void apply_increment(v::Pose& vue, const double delta[6], const Adl&)
  {
    for(size_t i = 0 ; i < 3 ; ++i)
      vue.translation()[i] += delta[i];
    v::apply_rotation(vue.rotation(), Eigen::Vector3d(delta[3],delta[4],delta[5]));
  }

  inline void apply_increment(v::UnifiedCameraModel& model, const double delta[5], const Adl&)
  {
    model.focal.x() += delta[0];
    model.focal.y() += delta[1];
    model.center.x() += delta[2];
    model.center.y() += delta[3];
    model.xi += delta[4];
  }

  template<int I> void apply_small_increment(v::UnifiedCameraModel& model, double d, v::numeric_tag<I>, const Adl&)
  {
    if (I==0)
      model.focal.x() += d;
    else if(I==1)
      model.focal.y() += d;
    else if(I==2)
      model.center.x() += d;
    else if(I==3)
      model.center.y() += d;
    else if(I==4)
      model.xi += d;
  }
}

struct Obs
{
  Eigen::Vector2d coord;
  int ipose;
  int i3d;
  Obs(){}
  Obs(const Eigen::Vector2d& v2d, int ipose_, int i3d_):coord(v2d),ipose(ipose_),i3d(i3d_){}
};

typedef AlignedVector<Eigen::Vector3d> P3DS;
typedef AlignedVector<Obs> P2DS;
typedef AlignedVector<v::Pose> Poses;

void draw(const v::Pose& pose, double d)
{

  glLineWidth(2);
  Eigen::Vector3d o1(0,0,0);
  Eigen::Vector3d v1(d,0,0);
  Eigen::Vector3d v2(0,d,0);
  Eigen::Vector3d v3(0,0,d);

  o1 = pose.rotation() * o1 + pose.translation();
  v1 = pose.rotation() * v1 + pose.translation();
  v2 = pose.rotation() * v2 + pose.translation();
  v3 = pose.rotation() * v3 + pose.translation();

  glBegin(GL_LINES);
  glColor3f(1.0,0.0,0.0);
  glVertex3f(o1.x(),o1.y(),o1.z());
  glVertex3f(v1.x(),v1.y(),v1.z());

  glColor3f(0.0,1.0,0.0);
  glVertex3f(o1.x(),o1.y(),o1.z());
  glVertex3f(v2.x(),v2.y(),v2.z());

  glColor3f(0.0,0.0,1.0);
  glVertex3f(o1.x(),o1.y(),o1.z());
  glVertex3f(v3.x(),v3.y(),v3.z());
  glEnd();
}

void draw(const P3DS& p3ds, const Poses& poses, const float d)
{
  glColor3f(1,0,0);
  glPointSize(2);
  glBegin(GL_POINTS);
  for(auto& p : p3ds)
    glVertex3dv(p.data());
  glEnd();

  for(auto& pose : poses)
    draw(pose,d);
}

bool projection(const v::UnifiedCameraModel& model, const v::Pose& pose, const Eigen::Vector3d& p3d, Eigen::Vector2d& p2d)
{
  Eigen::Vector3d p3dc = v::to_coordinate_system_of(pose,p3d);
  if (p3dc.z()<0.1) return false;
  return model.project(p3dc, p2d);
}

bool error(const v::UnifiedCameraModel& model, const v::Pose& pose, const Eigen::Vector3d& p3d, const Eigen::Vector2d& obs, Eigen::Vector2d& residual)
{
  Eigen::Vector2d p2d;
  bool success = projection(model,pose,p3d,p2d);
  residual = p2d - obs;
  return success;
}

struct Error
{
  const Eigen::Vector2d& obs;
  Error(const Eigen::Vector2d& obs_):obs(obs_){}

  bool operator()(const v::UnifiedCameraModel& model, const v::Pose& pose, const Eigen::Vector3d& p3d, Eigen::Vector2d& residual) const
  {
    return error(model,pose,p3d,obs,residual);
  }
};

int main()
{
  v::UnifiedCameraModel model(800,800,320,240,2.0);

  P3DS p3ds(1000);
  for(auto& p : p3ds)
    p = Eigen::Vector3d().Random()*50.0 + Eigen::Vector3d(0,0,400);

  Poses poses(10);
  for(auto& pose : poses)
    pose.translation(Eigen::Vector3d().Random()*100.0);

  P2DS p2ds;

  for(size_t i = 0 ; i < p3ds.size() ; ++i)
    for(size_t j = 0 ; j < poses.size() ; ++j)
    {
      Eigen::Vector2d p2d;
      if (projection(model,poses.at(j),p3ds.at(i),p2d))
      {
        p2ds.emplace_back(p2d,j,i);
      }
      else
      {
        std::cout << " p3d " << i << " avec la pose " << j << " ne se projette pas " << std::endl;
      }
    }

  for(auto& p : p3ds)
    p += Eigen::Vector3d().Random()*50.0;

  v::viewer(0).size(800,600).title("3D").interaction_mode(v::INTERACTION_CAD).add_opengl(boost::bind(draw,p3ds,poses,30)).update();

  std::cout << " MODEL ORIGINAL : " << model.focal.transpose() << " ; " << model.center.transpose() << " ; " << model.xi << std::endl;

  model = v::UnifiedCameraModel(750,850,300,200,1.5);

  std::cout << " MODEL BRUITER : " << model.focal.transpose() << " ; " << model.center.transpose() << " ; " << model.xi << std::endl;

  lma::Solver<Error> solver(-1,500,0.999999999);

  for(auto& obs : p2ds)
    solver.add(Error(obs.coord),&model,&poses.at(obs.ipose),&p3ds.at(obs.i3d));

  solver.solve(lma::DENSE_SCHUR,lma::enable_verbose_output());
  // changement de repère monde -> caméra

  // std::cout << " Coordonnées du point dans l'image : " << p2d.transpose() << std::endl;
  std::cout << " MODEL APRES OPTIMISATION : " << model.focal.transpose() << " ; " << model.center.transpose() << " ; " << model.xi << std::endl;

  v::viewer(0).clear().size(800,600).title("3D").interaction_mode(v::INTERACTION_CAD).add_opengl(boost::bind(draw,p3ds,poses,30)).update();

  v::ViewerContext view = v::viewer(1).title("2D").size(640,480).pen_width(5).pen_color(v::red);
  for(auto& p : p2ds)
  {
    if (p.ipose==0)
      view.add_point(p.coord.x(),p.coord.y());
  }
  view.update();

   v::wait_viewers();

  return 0;
}

max_stars_repo_name: bezout/LMA

max_issues_repo_name: ayumizll/LMA

max_forks_repo_name: bezout/LMA


text:
/*
 * Copyright (c) 2018-2022 curoky(cccuroky@gmail.com).
 *
 * This file is part of my-own-x.
 * See https://github.com/curoky/my-own-x for further info.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <boost/lexical_cast.hpp>  // for lexical_cast, bad_lexical_cast
#include <catch2/catch.hpp>  // for operator""_catch_sr, AssertionHandler, SourceLineInfo, StringRef, REQUIRE, REQUIRE_THROWS_AS, TEST_CASE

#include <sstream>  // for basic_stringbuf<>::int_type, basic_stringbuf<>::pos_type, basic_stringbuf<>::__streambuf_type, ios_base::failure
#include <string>   // for string, basic_string, operator==

TEST_CASE("[Lexical-cast]: BaseTest") {
  // string <=> int
  REQUIRE(boost::lexical_cast<int>("-123") == -123);
  REQUIRE(boost::lexical_cast<std::string>(-123) == "-123");

  // string <=> double
  REQUIRE(boost::lexical_cast<double>("-123.12") == -123.12);
  REQUIRE(boost::lexical_cast<std::string>(-123.12) == "-123.12");
}

TEST_CASE("[Lexical-cast]: bad cast") {
  REQUIRE_THROWS_AS(boost::lexical_cast<int>("123;"), boost::bad_lexical_cast);
  REQUIRE_THROWS_AS(boost::lexical_cast<int>("123.13.123"), boost::bad_lexical_cast);
  REQUIRE_THROWS_AS(boost::lexical_cast<int>("123i"), boost::bad_lexical_cast);
  REQUIRE_THROWS_AS(boost::lexical_cast<int>("abc"), boost::bad_lexical_cast);
}

ext: cc

max_stars_repo_name: curoky/my-own-x

max_issues_repo_name: curoky/my-own-x

max_forks_repo_name: curoky/my-own-x


text:
//-----------------------------------------------------------------------------
// Copyright (c) 2015-2018 Benjamin Buch
//
// https://github.com/bebuch/disposer
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
//-----------------------------------------------------------------------------
#ifndef _disposer__core__make_input__hpp_INCLUDED_
#define _disposer__core__make_input__hpp_INCLUDED_

#include "input_name.hpp"
#include "dimension_solve.hpp"
#include "output_base.hpp"
#include "dimension_referrer_output.hpp"

#include "../config/module_make_data.hpp"

#include "../tool/to_std_string_view.hpp"

#include <boost/algorithm/string/replace.hpp>

#include <array>
#include <variant>
#include <unordered_map>

namespace disposer{

	/// \brief Provids types for constructing an input
	template <
		typename Name,
		typename DimensionReferrer,
		bool IsRequired >
	struct input_maker{
		/// \brief Tag for boost::hana
		using hana_tag = input_maker_tag;

		/// \brief Dimension dependence of the type
		using dimension_referrer = DimensionReferrer;

		/// \brief input_name object
		static constexpr auto name = Name{};

		/// \brief True if is type is not dependet on anything
		static constexpr bool is_free_type = DimensionReferrer::is_free_type;

		/// \brief Description of the input
		template < typename ... DTs >
		std::string help_text_fn(dimension_list< DTs ... >)const{
			std::ostringstream help;
			help << "    * input: "
				<< detail::to_std_string_view(name) << "\n";
			help << help_text << "\n";
			help << wrapped_type_ref_text(
				DimensionReferrer{}, dimension_list< DTs ... >{});
			return help.str();
		}

		/// \brief User defined help text
		std::string const help_text;
	};

	/// \brief Configuration class for inputs
	template < bool IsRequired >
	struct is_required: std::bool_constant< IsRequired >{};

	/// \brief Used as make-function argument of inputs
	constexpr auto required = is_required< true >{};

	/// \brief Used as make-function argument of inputs
	constexpr auto not_required = is_required< false >{};

	/// \brief Creates a \ref input_maker object
	template <
		char ... C,
		template < typename ... > typename Template,
		std::size_t ... D,
		bool IsRequired = true >
	auto make(
		input_name< C ... > const&,
		dimension_referrer< Template, D ... > const&,
		std::string const& description,
		is_required< IsRequired > = required
	){
		return input_maker<
			input_name< C ... >,
			dimension_referrer< Template, D ... >,
			IsRequired >{
				"      * " +
				boost::replace_all_copy(description, "\n", "\n        ")
			};
	}

	inline output_base* get_output_ptr(
		input_list const& inputs,
		std::string_view const& name
	){
		auto const iter = inputs.find(name);
		return iter != inputs.end() ? iter->second : nullptr;
	}

	template <
		typename Name,
		typename DimensionReferrer,
		bool IsRequired,
		typename ... Ds,
		bool ... KDs,
		typename ... Ts >
	auto deduce_dimensions_by_input(
		input_maker< Name, DimensionReferrer, IsRequired >,
		dimension_list< Ds ... >,
		output_base* const output_ptr
	){
		if constexpr(IsRequired){
			constexpr dimension_solver solver(
				dimension_list< Ds ... >{},
				DimensionReferrer{});
			return solver.solve(Name{}, output_ptr->get_type());
		}else{
			(void)output_ptr; // Silance GCC
			return solved_dimensions{};
		}
	}

}

#endif

ext: hpp

max_stars_repo_name: bebuch/disposer

max_issues_repo_name: bebuch/disposer

max_forks_repo_name: bebuch/disposer


text:
/*
    Copyright 2019 Tenable, Inc.                                                                                *

    Redistribution and use in source and binary forms, with or without modification,
    are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this
        list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright notice,
        this list of conditions and the following disclaimer in the documentation
        and/or other materials provided with the distribution.

    3. Neither the name of the copyright holder nor the names of its contributors
        may be used to endorse or promote products derived from this software
        without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/
#include <list>
#include <regex>
#include <cstdlib>
#include <fstream>
#include <ctime>
#include <iostream>
#include <boost/cstdint.hpp>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <GeoLite2PP.hpp>

#include "winbox_session.hpp"
#include "winbox_message.hpp"

namespace
{
    const char s_version[] = "Winbox Scanner 1.1";

    bool parseCommandLine(int p_argCount, const char* p_argArray[],
                          std::string& p_ipFile, std::string& p_outFile,
                          bool& p_list_scan, bool& p_index_scan)
    {
        boost::program_options::options_description description("options");
        description.add_options()
            ("help,h", "A list of command line options")
            ("version,v", "Display version information")
            ("in,i", boost::program_options::value<std::string>(), "The list of addresses to scan")
            ("out,o", boost::program_options::value<std::string>(), "The file to write to")
            ("list_scan", boost::program_options::value<bool>()->default_value(false), "Use the mproxy 2,2 list method")
            ("index_scan", boost::program_options::value<bool>()->default_value(false), "Use the option 2 index method");

        boost::program_options::variables_map argv_map;
        try
        {
            boost::program_options::store(
                boost::program_options::parse_command_line(
                    p_argCount, p_argArray, description), argv_map);
        }
        catch (const std::exception& e)
        {
            std::cerr << e.what() << std::endl;
            std::cerr << description << std::endl;
            return false;
        }

        boost::program_options::notify(argv_map);
        if (argv_map.empty() || argv_map.count("help"))
        {
            std::cerr << description << std::endl;
            return false;
        }

        if (argv_map.count("version"))
        {
            std::cerr << "Version: " << ::s_version << std::endl;
            return false;
        }

        if (argv_map.count("in") && argv_map.count("out") &&
            (argv_map.count("list_scan") || argv_map.count("index_scan")))
        {
            p_ipFile.assign(argv_map["in"].as<std::string>());
            p_outFile.assign(argv_map["out"].as<std::string>());
            p_list_scan = argv_map["list_scan"].as<bool>();
            p_index_scan = argv_map["index_scan"].as<bool>();
            return true;
        }
        else
        {
            std::cout << description << std::endl;
        }

        return false;
    }

    void do_list_scan(const std::string& p_address, const std::string& p_geo, std::ofstream& p_csv_results)
    {
        Winbox_Session winboxSession(p_address, "8291");
        if (!winboxSession.connect())
        {
            return;
        }

        std::string list;
        bool result = winboxSession.old_mproxy_get_file("list", list);
        if (result == false)
        {
            if (list.empty())
            {
                return;
            }
            else
            {
                p_csv_results << p_address << "|" << p_geo<< "|" << "old_ver" << std::endl;
                return;
            }
        }
        else
        {
            if (list.empty())
            {
                p_csv_results << p_address << "|" << p_geo << "|" << "new_ver" << std::endl;
                return;
            }
        }

        if (!list.empty())
        {
            std::smatch matches;
            // version: "6.39.3"
            std::regex version_match("version: \"([^\"]+)\"");
            std::regex_search(list, matches, version_match);
            if (!matches.empty())
            {
                p_csv_results << p_address << "|" << p_geo << "|" << matches[1] << std::endl;
                return;
            }
        }

        p_csv_results << p_address << "|" << p_geo << "|" << "unknown" << std::endl;
    }

    void do_index_scan(const std::string& p_address, const std::string& p_geo, std::ofstream& p_csv_results)
    {
        Winbox_Session winboxSession(p_address, "8291");
        if (!winboxSession.connect())
        {
            return;
        }

        std::string index;
        if (!winboxSession.old_mproxy_get_file("index", index))
        {
            return;
        }

        if (!index.empty())
        {
            std::smatch matches;
            // version: "6.39.3"
            std::regex version_match("roteros.dll ([^\\n]+)");
            std::regex_search(index, matches, version_match);
            if (!matches.empty())
            {
                p_csv_results << p_address << "|" << p_geo << "|" << matches[1] << std::endl;
                return;
            }
        }

        p_csv_results << p_address << "|" << p_geo << "|" << "unknown" << std::endl;
    }
}

int main(int p_argc, const char** p_argv)
{
    std::string ipList;
    std::string outFile;
    bool list_scan = false;
    bool index_scan = false;
    if (!parseCommandLine(p_argc, p_argv, ipList, outFile, list_scan, index_scan))
    {
        return EXIT_FAILURE;
    }

    GeoLite2PP::DB geoDB("/var/lib/GeoIP/GeoLite2-City.mmdb");

    std::cout << "[+] Creating output file." << std::endl;
    std::ofstream csv_results(outFile);
    if (!csv_results.is_open())
    {
        std::cerr << "Couldn't create the results file." << std::endl;
        return EXIT_FAILURE;
    }

    std::cout << "[+] Loading IP address list..." << std::endl;
    std::ifstream ipFile(ipList);
    if (!ipFile.is_open())
    {
        std::cerr << "Couldn't open the IP file." << std::endl;
        return EXIT_FAILURE;
    }

    // load all the ips into a list beforehand, I guess.
    std::list<std::pair<std::string, std::string> > ip_list;

    std::string ip_address;
    while (std::getline(ipFile, ip_address))
    {
        if (ip_address.empty())
        {
            continue;
        }
        std::string country = "unknown";
        try
        {
            country = geoDB.get_field(ip_address, "en", GeoLite2PP::VCStr { "country", "names" });
        }
        catch (const std::exception&)
        {
        }
        ip_list.push_back(std::make_pair(ip_address, country));
        ip_address.clear();
    }
    ipFile.close();

    std::cout << "[!] " << ip_list.size() << " IP addresses loaded" << std::endl;

    int start = time(NULL);
    double per_second = 0;
    int count = 1;
    for (std::list<std::pair< std::string, std::string> >::const_iterator iter = ip_list.begin();
        iter != ip_list.end(); iter++, count++)
    {
        if ((count % 100) == 0)
        {
            per_second = (double)(time(NULL) - start) / count;
        }

        std::cout << "\r" << count << " / " << ip_list.size() << " | " << per_second << " per second" << std::flush;

        try
        {
            if (list_scan)
            {
                do_list_scan(iter->first, iter->second, csv_results);
            }
            else if (index_scan)
            {
                do_index_scan(iter->first, iter->second, csv_results);
            }
            else
            {
                std::cerr << "Do nothing?" << std::endl;
                return EXIT_FAILURE;
            }
        }
        catch (const std::exception&)
        {
        }
    }

    csv_results.close();

    return EXIT_SUCCESS;
}

ext: cpp

max_stars_repo_name: Bram-Wel/routeros

max_issues_repo_name: Bram-Wel/routeros

max_forks_repo_name: Bram-Wel/routeros


text:
// ImGui - standalone example application for DirectX 9
// If you are new to ImGui, see examples/README.txt and documentation at the top of imgui.cpp.

#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <boost/chrono.hpp>
#include "imgui.h"
#include "imgui_impl_dx9.h"
#include <d3d9.h>
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
#include <tchar.h>
#include <d3dx9.h>
#include <ctime>
#include <fstream>
#include <sstream>
#include <iostream>
#include <cstdlib>
#include <string>
#include <vector>

/////////////////////////////////////////////////////////
//
//	Boost file system conflict with std library
// 	Should of seen that comming :P
//
//	Header contains file open/save ^_^'
//	This means rewriting load/save code.
//
//	#include <boost/filesystem.hpp>
//	using namespace boost::filesystem;
//
///////////////////////////////////////////////////////
//
//	Boost::Asio
//
//	#include <boost/asio/ip/tcp.hpp>
//
//	Basic networking component, it handles tcp/ip.
//	also supoort for other socket protocols
//	(such as Bluetooth or IRCOMM sockets)
//
//	This will get me HTTP 1.0 support (Text)
//	Below is the full http_client source code.
//
//	Slowly reworking this into my Minimal browser.
//
//	UPDATE 1
//
//	I have the entire boost library built.
//	Said library works. I have got sockets =)!!
//
// Grabbed Cef binaries and turned the .libs
//	For the DLL shared linkers to .A format using reimp
//	This will give me HTML 5!! suppprt.
//
//
/////////////////////////////////////////////////////////////
//
//	Threading resources & calls
//
//
void cmd()
{
system("cmd");
}
void lua()
{
system("lua");
}
void ipconfigure_bat()
{
system("ipconfigure.bat");
}
void ipconfigure_netstat_on_bat()
{
system("ipconfigure.netstat.on.bat");
}
void ipconfigure_netstat_a_bat()
{
system("ipconfigure.netstat.a.bat");
}
void ipconfigure_netstat_o_bat()
{
system("ipconfigure.netstat.o.bat");
}
void ipconfigure_netstat_t_bat()
{
system("ipconfigure.netstat.t.bat");
}
void ipconfigure_netstat_f_bat()
{
system("ipconfigure.netstat.f.bat");
}
void ipconfigure_wmic_bat()
{
system("ipconfigure.wmic.bat");
}
void ipconfigure_wmic_help_bat()
{
system("ipconfigure.wmic.help.bat");
}
/////////////////////////////////////////////////////////////
//using boost::asio::ip::tcp;
using namespace std;
// Data
static LPDIRECT3DDEVICE9        g_pd3dDevice = NULL;
static D3DPRESENT_PARAMETERS    g_d3dpp;

extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
        return true;

    switch (msg)
    {
    case WM_SIZE:
        if (g_pd3dDevice != NULL && wParam != SIZE_MINIMIZED)
        {
            ImGui_ImplDX9_InvalidateDeviceObjects();
            g_d3dpp.BackBufferWidth  = LOWORD(lParam);
            g_d3dpp.BackBufferHeight = HIWORD(lParam);
            HRESULT hr = g_pd3dDevice->Reset(&g_d3dpp);
            if (hr == D3DERR_INVALIDCALL)
                IM_ASSERT(0);
            ImGui_ImplDX9_CreateDeviceObjects();
        }
        return 0;
    case WM_SYSCOMMAND:
        if ((wParam & 0xfff0) == SC_KEYMENU) // Disable ALT application menu
            return 0;
        break;
    case WM_DESTROY:
        PostQuitMessage(0);
        return 0;
    }
    return DefWindowProc(hWnd, msg, wParam, lParam);
}

int main(int, char**)
{
    // Create application window
    WNDCLASSEX wc = { sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0L, 0L, GetModuleHandle(NULL), NULL, LoadCursor(NULL, IDC_ARROW), NULL, NULL, _T("ImGui Example"), NULL };
    RegisterClassEx(&wc);
    HWND hwnd = CreateWindow(_T("ImGui Example"), _T("LUA.Editor"), WS_OVERLAPPEDWINDOW, 0, 0, 1280, 800, NULL, NULL, wc.hInstance, NULL);

    // Initialize Direct3D
    LPDIRECT3D9 pD3D;
    if ((pD3D = Direct3DCreate9(D3D_SDK_VERSION)) == NULL)
    {
        UnregisterClass(_T("ImGui Example"), wc.hInstance);
        return 0;
    }
    ZeroMemory(&g_d3dpp, sizeof(g_d3dpp));
    g_d3dpp.Windowed = TRUE;
    g_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
    g_d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
    g_d3dpp.EnableAutoDepthStencil = TRUE;
    g_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
    g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE; // Present with vsync

    //g_d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; // Present without vsync, maximum unthrottled framerate

    // Create the D3DDevice
    if (pD3D->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &g_d3dpp, &g_pd3dDevice) < 0)
    {
        pD3D->Release();
        UnregisterClass(_T("ImGui Example"), wc.hInstance);
        return 0;
    }

    // Setup ImGui binding
    ImGui_ImplDX9_Init(hwnd, g_pd3dDevice);

    // Setup style
    ImGui::StyleColorsDark();
    //ImGui::StyleColorsClassic();

    // Load Fonts
    // - If no fonts are loaded, dear imgui will use the default font. You can also load multiple fonts and use ImGui::PushFont()/PopFont() to select them.
    // - AddFontFromFileTTF() will return the ImFont* so you can store it if you need to select the font among multiple.
    // - If the file cannot be loaded, the function will return NULL. Please handle those errors in your application (e.g. use an assertion, or display an error and quit).
    // - The fonts will be rasterized at a given size (w/ oversampling) and stored into a texture when calling ImFontAtlas::Build()/GetTexDataAsXXXX(), which ImGui_ImplXXXX_NewFrame below will call.
    // - Read 'misc/fonts/README.txt' for more instructions and details.
    // - Remember that in C/C++ if you want to include a backslash \ in a string literal you need to write a double backslash \\ !
    //ImGuiIO& io = ImGui::GetIO();
    //io.Fonts->AddFontDefault();
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Roboto-Medium.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/Cousine-Regular.ttf", 15.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/DroidSans.ttf", 16.0f);
    //io.Fonts->AddFontFromFileTTF("../../misc/fonts/ProggyTiny.ttf", 10.0f);
    //ImFont* font = io.Fonts->AddFontFromFileTTF("c:\\Windows\\Fonts\\ArialUni.ttf", 18.0f, NULL, io.Fonts->GetGlyphRangesJapanese());
    //IM_ASSERT(font != NULL);

/////////////////////////////////////////////////////////////
//
//	Window bools.
//
////////////////////////////////////////////////////////////
bool show_editor_window 		= true;			// Editor options selector
bool show_welcome				= true;			// Welcome screen/notes/changes loads out of "while"
bool show_about_editor			= false;		// Blurb
bool show_new_wizard			= false;		// Uses prefabs via loading
bool show_compiler				= false;		// Standard cmd call
bool show_run					= false;		// Runs Lua
bool show_save					= false;		// Fully func
bool show_open					= false;		// Fully func
bool show_help_support			= false;		// implement in program web browser?
bool show_options				= false;		// Uses inbuilt imgui call
bool show_IO					= false;		// Fully func
bool show_batch					= false;		// Fully func
bool show_prefab_list			= false;		// Ease of grabbing test scripts
bool show_save_complete			= false;		// Clickable
bool load_snippets				= true;			// Saveable / Loading called out of "while"
bool show_right_click_menu		= false;		// WIP Feature
bool show_guiopen				= false;		// WIP Open file explorer.
bool show_guisave				= false;		// WIP Save file explorer.
bool show_inprogram_dbg			= false;		// Debugger for web browser.
////////////////////////////////////////////////////////////
//
// Web browser bool & functionality.
//
//
bool show_web_browser			= false;		// WIP beast locksup my IDE! / ASIO seems to work.
bool show_web_settings			= false;		// Homepage/Downloads location/ssl/ftp/others
bool save_ftp_login				= false;		// Saved as binary fileformat. STILL WIP
bool mobile_html				= false;		// Mobile phone HTML only. look into me more.
bool status_empty				= true;			// Connection status indicators.
bool status_red					= false;		// "
bool status_yellow				= false;		// "
bool status_green				= false;		// "
bool save_cloud_login			= false;		// Saved as binary fileformat. STILL WIP
bool show_download_manager		= false;		// Used for upstream/downstream progress.
bool show_bookmarks_saved		= false;		// Displays user defined bookmarks

static char bookmarks_kept[1024*16];			// Bookmarks for browser.

static ImGuiOnceUponAFrame Browser_settings;	// Bookmarks & browser settings.
				if (Browser_settings)			// Will have to use my regex load here to parse data.
					{
            			ifstream file("Bookmarks.setting", ios::in|ios::ate);
            			if (file.is_open())
            				{
							streampos size;
					  		size = file.tellg();
							file.seekg (0, ios::beg);
							file.read (bookmarks_kept, size);
							file.close();
							}
					}

////////////////////////////////////////////////////////////
//
// Windows and arrays.
//
bool Work_space_one				= false;
bool Work_space_two				= false;
bool Work_space_three			= false;

static char Workspace1[1024*16];
static char Workspace2[1024*16];
static char Workspace3[1024*16];
////////////////////////////////////////////////////////////
//
// Welcome details.
//
static char Welcome[1024*16];
static ImGuiOnceUponAFrame once;
				if (once)
					{
            			ifstream file("Details.txt", ios::in|ios::ate);
            			if (file.is_open())
            				{
							streampos size;
					  		size = file.tellg();
							file.seekg (0, ios::beg);
							file.read (Welcome, size);
							file.close();
							}
					}
////////////////////////////////////////////////////////////
//
//	Copy.bat.
//
static char luaDIR[1024] = "copy *.lua ";
static char outDIR[1024] = "copy *.out ";
/////////////////////////////////////////////////////////////
//
// load selection.
//
bool load_selected_one			= false;
bool load_selected_two			= false;
bool load_selected_three		= false;
/////////////////////////////////////////////////////////////
//
// Save selection.
//
bool save_selected_one			= false;
bool save_selected_two			= false;
bool save_selected_three		= false;

/////////////////////////////////////////////////////////////
//
//	RGBA colour for screen.
//
ImVec4 clear_color = ImVec4(0.073f, 0.115f, 0.177f, 1.000f);
//////////////////////////////////////////////////////////////
//
//	Code snippets.
//
static char Codesnippets[1024*16];

static ImGuiOnceUponAFrame OnceAgain;
				if (OnceAgain)
					{
            			ifstream file("Snippets.txt", ios::in|ios::ate);
            			if (file.is_open())
            				{
							streampos size;
					  		size = file.tellg();
							file.seekg (0, ios::beg);
							file.read (Codesnippets, size);
							file.close();
							}
					}
////////////////////////////////////////////////////////////////////////////////
//
//	ICONS.
//
///////////////////////////////////////////////////////////////
static LPDIRECT3DTEXTURE9       filenew 		= NULL;		// image idents here. here =)
static LPDIRECT3DTEXTURE9       fileopen 		= NULL;
static LPDIRECT3DTEXTURE9       filesave 		= NULL;
static LPDIRECT3DTEXTURE9       settings 		= NULL;
static LPDIRECT3DTEXTURE9       IO 				= NULL;
static LPDIRECT3DTEXTURE9       compile 		= NULL;
static LPDIRECT3DTEXTURE9       run 			= NULL;
static LPDIRECT3DTEXTURE9       source 			= NULL;
static LPDIRECT3DTEXTURE9       help 			= NULL;
static LPDIRECT3DTEXTURE9       Editor 			= NULL;
static LPDIRECT3DTEXTURE9       batch 			= NULL;
static LPDIRECT3DTEXTURE9       up 				= NULL;
static LPDIRECT3DTEXTURE9       web 			= NULL;
static LPDIRECT3DTEXTURE9       home 			= NULL;
static LPDIRECT3DTEXTURE9       back 			= NULL;
static LPDIRECT3DTEXTURE9       forward 		= NULL;
static LPDIRECT3DTEXTURE9       stop	 		= NULL;
static LPDIRECT3DTEXTURE9       downloads		= NULL;
static LPDIRECT3DTEXTURE9       bookmarks		= NULL;
static LPDIRECT3DTEXTURE9       statusempty		= NULL;
static LPDIRECT3DTEXTURE9       statusred		= NULL;
static LPDIRECT3DTEXTURE9       statusyellow	= NULL;
static LPDIRECT3DTEXTURE9       statusgreen		= NULL;
static LPDIRECT3DTEXTURE9       pause			= NULL;
static LPDIRECT3DTEXTURE9       resume			= NULL;

D3DXCreateTextureFromFile( g_pd3dDevice, "filenew.png" ,	 &filenew );			// image file grabs here :)
D3DXCreateTextureFromFile( g_pd3dDevice, "fileopen.png" ,	 &fileopen );
D3DXCreateTextureFromFile( g_pd3dDevice, "filesave.png" ,	 &filesave );
D3DXCreateTextureFromFile( g_pd3dDevice, "mechanical.png" ,	 &settings );
D3DXCreateTextureFromFile( g_pd3dDevice, "folder.png" ,		 &IO );
D3DXCreateTextureFromFile( g_pd3dDevice, "compile.png" ,	 &compile );
D3DXCreateTextureFromFile( g_pd3dDevice, "source.png" ,		 &source );
D3DXCreateTextureFromFile( g_pd3dDevice, "compilerun.png" ,	 &run );
D3DXCreateTextureFromFile( g_pd3dDevice, "runbatch.png" ,	 &batch );
D3DXCreateTextureFromFile( g_pd3dDevice, "addition.png" ,	 &help );
D3DXCreateTextureFromFile( g_pd3dDevice, "LUA.Editor.png" ,	 &Editor );
D3DXCreateTextureFromFile( g_pd3dDevice, "up.png" ,	 		 &up );
D3DXCreateTextureFromFile( g_pd3dDevice, "web.png" ,	 	 &web );
D3DXCreateTextureFromFile( g_pd3dDevice, "home.png" ,	 	 &home );
D3DXCreateTextureFromFile( g_pd3dDevice, "back.png" ,	 	 &back );
D3DXCreateTextureFromFile( g_pd3dDevice, "forward.png" ,	 &forward );
D3DXCreateTextureFromFile( g_pd3dDevice, "stop.png" ,		 &stop );
D3DXCreateTextureFromFile( g_pd3dDevice, "downloads.png" ,	 &downloads );
D3DXCreateTextureFromFile( g_pd3dDevice, "bookmarks.png" ,	 &bookmarks );
D3DXCreateTextureFromFile( g_pd3dDevice, "statusempty.png" , &statusempty );
D3DXCreateTextureFromFile( g_pd3dDevice, "statusred.png" , 	 &statusred );
D3DXCreateTextureFromFile( g_pd3dDevice, "statusyellow.png" ,&statusyellow );
D3DXCreateTextureFromFile( g_pd3dDevice, "statusgreen.png" , &statusgreen );
D3DXCreateTextureFromFile( g_pd3dDevice, "pause.png" , 		 &pause );
D3DXCreateTextureFromFile( g_pd3dDevice, "run.png" , 		 &resume );
//////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////

    // Main loop
    MSG msg;
    ZeroMemory(&msg, sizeof(msg));
    ShowWindow(hwnd, SW_SHOWDEFAULT);
    UpdateWindow(hwnd);
    while (msg.message != WM_QUIT)
    {
        // You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
        // - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
        // - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
        // Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
        if (PeekMessage(&msg, NULL, 0U, 0U, PM_REMOVE))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
            continue;
        }									   ///////////////////////////////////////////
        ImGui_ImplDX9_NewFrame();             // IT ALL STARTS HERE
//////////////////////////////////////////////////////////////
//
//	Mouse WIP COPY/PASTE.
//

static char right_click_selection[40];
static int right_menu_selection = -1;

		if(ImGui::IsMouseClicked( 1,true))
		{
				static ImGuiOnceUponAFrame fourth;
				if (fourth)
				{
					show_right_click_menu = true;
				}
		}
		if(ImGui::IsMouseClicked(0,true))
		{
				static ImGuiOnceUponAFrame fourth;
				if (fourth)
				{
					show_right_click_menu = false;
				}
		}
		if(show_right_click_menu)
		{
			ImVec2 base_pos = ImGui::GetMousePos();
			ImGui::SetNextWindowPos(ImVec2(base_pos.x,base_pos.y),ImGuiCond_Appearing);
			ImGui::SetNextWindowSize(ImVec2(100,105));
			ImGui::Begin("###rightmenu", &show_right_click_menu,ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize);
			ImGui::BeginChild("####rightmenu", ImVec2(-1,-1), true,ImGuiWindowFlags_NoScrollbar);
            sprintf(right_click_selection, "  Copy", 1);
            if (ImGui::Selectable(right_click_selection, right_menu_selection == 1 ))
////////////////////////////////////////////////////////////////////
//
//	Still WIP instead of reinventing the wheel. Forceing CTRL+C hot.
//	Imgui`s built in copy function should pick the key combination up.
//	Same for paste operation. CTRL+V hot.
//
//	However proveing maddeningly difficult!
//	Will have to post a issue note on github.
//
//	Can also achieve the same with Redo/Undo.
//
//	Keys CTRL+Y: redo & CTRL+Z: undo.
//
//	Failed attemps below BUT keeping for github question to Omar Cornut.

			{
			right_menu_selection = 1; //show_right_click_menu = false;
			//ImGui::GetIO().KeyCtrl == true and ImGuiKey_C == true;
			//ImGui::IsKeyDown(ImGuiKey_C) == true;
			//IsKeyPressedMap(ImGuiKey_C) = true;
			//ImGuiKey_C == true;
			//ImGuiIO.KeyCtrl = true;ImGuiIO.KeysDown = ImGuiKey_C = true;
			}
			ImGui::Separator();
			sprintf(right_click_selection, "  Paste", 2);
            if (ImGui::Selectable(right_click_selection, right_menu_selection == 2 )){right_menu_selection = 2;}
   			ImGui::Separator();
			sprintf(right_click_selection, "  Redo", 3);
            if (ImGui::Selectable(right_click_selection, right_menu_selection == 3 )){right_menu_selection = 3;}
   			ImGui::Separator();
			sprintf(right_click_selection, "  Undo", 4);
            if (ImGui::Selectable(right_click_selection, right_menu_selection == 4 )){right_menu_selection = 4;}

			ImGui::EndChild();
			ImGui::End();
		}
//////////////////////////////////////////////////////////////
//
//	New Wizard check boxes & selectables.
//
static char new_wizard_selection_workspace[40];
static int selectedworkspace = -1;

/////////////////////////////////////////////////////////////
//
//	Workspace window create. WIP Changing layout, adding menu bars.
//
//	Workspace #1

if (Work_space_one)
{
ImGui::Begin("Workspace #1", &Work_space_one, ImGuiWindowFlags_MenuBar);
ImGui::InputTextMultiline("##Workspace1", Workspace1, IM_ARRAYSIZE(Workspace1), ImVec2(-1.0f, -1.0 * 16), ImGuiInputTextFlags_AllowTabInput );
	if (ImGui::BeginMenuBar())
	{
	if (ImGui::BeginMenu("Options"))
		{
    		ImGui::MenuItem("  New", NULL);
    		if (ImGui::MenuItem("  Save", NULL)){show_save = true;}
    		if (ImGui::MenuItem("  Open", NULL)){show_open = true;}
    		ImGui::MenuItem("  Open recent", NULL);
    		if(ImGui::BeginMenu("  Insert"))
    		{
    			ImGui::MenuItem("Box comment", NULL);
    			ImGui::MenuItem("Time & Date", NULL);

    			ImGui::EndMenu();
			}
			if(ImGui::BeginMenu("  Edit"))
    		{
    			ImGui::MenuItem("Indent", NULL);
    			ImGui::MenuItem("Unindent", NULL);

    			ImGui::EndMenu();
			}
    		ImGui::EndMenu();
		}
	ImGui::EndMenuBar();
	}
ImGui::End();
}

//	Workspace #2

if (Work_space_two)
{
ImGui::Begin("Workspace #2", &Work_space_two,ImGuiWindowFlags_MenuBar);
ImGui::InputTextMultiline("##Workspace2", Workspace2, IM_ARRAYSIZE(Workspace2), ImVec2(-1.0f, -1.0 * 16), ImGuiInputTextFlags_AllowTabInput);
	if (ImGui::BeginMenuBar())
	{
	if (ImGui::BeginMenu("Options"))
		{
    		ImGui::MenuItem("  New", NULL);
    		if (ImGui::MenuItem("  Save", NULL)){show_save = true;}
    		if (ImGui::MenuItem("  Open", NULL)){show_open = true;}
    		ImGui::MenuItem("  Open recent", NULL);
    		if(ImGui::BeginMenu("  Insert"))
    		{
    			ImGui::MenuItem("Box comment", NULL);
    			ImGui::MenuItem("Time & Date", NULL);

    			ImGui::EndMenu();
			}
			if(ImGui::BeginMenu("  Edit"))
    		{
    			ImGui::MenuItem("Indent", NULL);
    			ImGui::MenuItem("Unindent", NULL);

    			ImGui::EndMenu();
			}
    		ImGui::EndMenu();
		}
	ImGui::EndMenuBar();
	}
ImGui::End();
}

//	Workspace #3

if (Work_space_three)
{
ImGui::Begin("Workspace #3", &Work_space_three,ImGuiWindowFlags_MenuBar);
ImGui::InputTextMultiline("##Workspace3", Workspace3, IM_ARRAYSIZE(Workspace3), ImVec2(-1.0f, -1.0 * 16), ImGuiInputTextFlags_AllowTabInput);
	if (ImGui::BeginMenuBar())
	{
	if (ImGui::BeginMenu("Options"))
		{
    		ImGui::MenuItem("  New", NULL);
    		if (ImGui::MenuItem("  Save", NULL)){show_save = true;}
    		if (ImGui::MenuItem("  Open", NULL)){show_open = true;}
    		ImGui::MenuItem("  Open recent", NULL);
    		if(ImGui::BeginMenu("  Insert"))
    		{
    			ImGui::MenuItem("Box comment", NULL);
    			ImGui::MenuItem("Time & Date", NULL);

    			ImGui::EndMenu();
			}
			if(ImGui::BeginMenu("  Edit"))
    		{
    			ImGui::MenuItem("Indent", NULL);
    			ImGui::MenuItem("Unindent", NULL);

    			ImGui::EndMenu();
			}
    		ImGui::EndMenu();
		}
	ImGui::EndMenuBar();
	}
ImGui::End();
}

/////////////////////////////////////////////////////////////
//
//	Editor and other windows.
//

		show_editor_window 	= true; // Not close-able.

		if (show_welcome)
		{
			ImGui::Begin("Welcome screen", &show_welcome);
			ImGui::Text("");
			ImGui::SameLine(ImGui::GetWindowContentRegionWidth()/2 -95);
			ImGui::Image((void *)Editor, ImVec2(200, 200), ImVec2(0,0),ImVec2(1,1),ImVec4(255,255,255,255),ImVec4(0,0,0,0));
			ImGui::Separator();
			ImGui::InputTextMultiline("##Welcome", Welcome, IM_ARRAYSIZE(Welcome), ImVec2(-1.0f, -1.0 * 16), ImGuiInputTextFlags_AllowTabInput | ImGuiInputTextFlags_ReadOnly);
            ImGui::End();
		}
		if (show_editor_window)
		{
			ImGui::Begin("Editor Tools", &show_editor_window);
			ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
            ImGui::BeginChild("####menu", ImVec2(-1,35), true,ImGuiWindowFlags_NoScrollbar);

			if(ImGui::ImageButton((void *)filenew, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){show_new_wizard = true;}
            if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("New");ImGui::EndTooltip();}

			ImGui::SameLine();
			if(ImGui::ImageButton((void *)fileopen, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){show_open = true;}
			if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Open");ImGui::EndTooltip();}

			ImGui::SameLine();
			if(ImGui::ImageButton((void *)filesave, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){show_save = true;}
			if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Save");ImGui::EndTooltip();}

			ImGui::SameLine();
			if(ImGui::ImageButton((void *)IO, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){show_IO = true;}
			if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Output options");ImGui::EndTooltip();}

			ImGui::SameLine();
			if (ImGui::ImageButton((void *)batch, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){show_batch = true;}
			if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Run Batch -\nMoves saved .lua/.out output\nto desired folders");ImGui::EndTooltip();}
			if(show_batch == true){static ImGuiOnceUponAFrame once;if (once){system ("Copy.bat");show_batch = false;}}

			ImGui::SameLine();
			if (ImGui::ImageButton((void *)compile, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){static ImGuiOnceUponAFrame once;if (once){boost::thread_group threads;threads.create_thread(cmd);}}
			if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Compile");ImGui::EndTooltip();}

			ImGui::SameLine();
			if (ImGui::ImageButton((void *)run, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){static ImGuiOnceUponAFrame once;if (once){boost::thread_group threads;threads.create_thread(lua);}}
			if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Run");ImGui::EndTooltip();}

			ImGui::SameLine();
			if(ImGui::ImageButton((void *)settings, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){show_options = true;}
			if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Settings");ImGui::EndTooltip();}

			ImGui::SameLine();
			if (ImGui::ImageButton((void *)source, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255)))
			{show_about_editor = true;}
			if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("About");ImGui::EndTooltip();}

			ImGui::SameLine();
			if(ImGui::ImageButton((void *)help, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){show_help_support = true;}
			if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Help & Support");ImGui::EndTooltip();}

			ImGui::SameLine();
			if(ImGui::ImageButton((void *)web, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){show_web_browser = true;}
			if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Web browser");ImGui::EndTooltip();}

			ImGui::EndChild();
            ImGui::PopStyleVar();
            ImGui::Separator();
            ImGui::Text("Code Snippets");
            ImGui::Separator();
            ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
            ImGui::BeginChild("####codesnippets", ImVec2(-1,-1), true,ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse);
            ImGui::InputTextMultiline("##CodeCopyArea", Codesnippets, IM_ARRAYSIZE(Codesnippets), ImVec2(-1.0f, -1.0 * 16), ImGuiInputTextFlags_AllowTabInput);
			ImGui::Text("");
			ImGui::SameLine(ImGui::GetWindowContentRegionWidth()/2 -40);
			if(ImGui::Button("Save Snippets"))
			{
				ofstream save_data("Snippets.txt");
				if (save_data.is_open())
				{save_data << Codesnippets;save_data.close();show_save_complete = true;}
			}
			ImGui::EndChild();
            ImGui::PopStyleVar();
            ImGui::End();
       	}
		if (show_new_wizard)
		{
			ImGui::Begin("New wizard", &show_new_wizard);
			ImGui::Text("Choose Work space.");
			ImGui::Separator();
            ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
            ImGui::BeginChild("####newwizardworkspace", ImVec2(-1,100), true,ImGuiWindowFlags_NoScrollbar);
            sprintf(new_wizard_selection_workspace, "Work space #1", 1);
            if (ImGui::Selectable(new_wizard_selection_workspace, selectedworkspace == 1 )){selectedworkspace = 1;}
            sprintf(new_wizard_selection_workspace, "Work space #2", 2);
            if (ImGui::Selectable(new_wizard_selection_workspace, selectedworkspace == 2 )){selectedworkspace = 2;}
            sprintf(new_wizard_selection_workspace, "Work space #3", 3);
            if (ImGui::Selectable(new_wizard_selection_workspace, selectedworkspace == 3 )){selectedworkspace = 3;}
   			ImGui::EndChild();
            ImGui::PopStyleVar();
            ImGui::Separator();
            ImGui::Text("To select a premade script,\n"
						"Select a workspace use 'Open'\n"
						"from editor tools.");
            ImGui::Separator();
            if (ImGui::Button("Cancel",  ImVec2(50,0))) {  show_new_wizard = false; }
            ImGui::SameLine();
			if(ImGui::Button("Prefabs"))
			{
				show_open = true;
				show_prefab_list = true;
			}
			ImGui::SameLine(ImGui::GetWindowContentRegionWidth()-40,-1);
            if (ImGui::Button("Ok", ImVec2(50,0)))
			{
				static ImGuiOnceUponAFrame once;
				if (once)
				{
				if (selectedworkspace == 1){Work_space_one = true;}
				if (selectedworkspace == 2){Work_space_two = true;}
				if (selectedworkspace == 3){Work_space_three = true;}
				}
			}

            ImGui::End();
		}
		if (show_open)
		{
			ImGui::Begin("Open", &show_open);
			ImGui::Text("To open a file\n\n"
			"place script in the same location as LUA.Editor.exe\n\n"
			"Or navigate to the file using the UI button.\n"
			"Choose a Workspace to load the script into.\n\n"
			"Do not forget to add file extension.  .txt/.lua");
			ImGui::Separator();
			static char load_file[100] = ".lua";    // setup text filtering, could be in latest update.
            string load_name = load_file;
			ImGui::Checkbox("Workspace #1", &load_selected_one);
			ImGui::Checkbox("Workspace #2", &load_selected_two);
			ImGui::Checkbox("Workspace #3", &load_selected_three);
			ImGui::Separator();
			ImGui::InputText("#####open", load_file, IM_ARRAYSIZE(load_file), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll);
            ImGui::Separator();
			if (ImGui::Button("Open"))
			{
				if (load_selected_one == true && Work_space_one	== true)
				{ifstream file(load_name.c_str(), ios::in|ios::ate);if (file.is_open()){streampos size;size = file.tellg();file.seekg (0, ios::beg);file.read (Workspace1, size);file.close();}}

				if (load_selected_two == true && Work_space_two	== true)
				{ifstream file(load_name.c_str(), ios::in|ios::ate);if (file.is_open()){streampos size;size = file.tellg();file.seekg (0, ios::beg);file.read (Workspace2, size);file.close();}}

				if (load_selected_three == true && Work_space_three == true)
				{ifstream file(load_name.c_str(), ios::in|ios::ate);if (file.is_open()){streampos size;size = file.tellg();file.seekg (0, ios::beg);file.read (Workspace3, size);file.close();}}
			}
			ImGui::SameLine();
			if(ImGui::Button("UI Open"))
			{show_guiopen = true;}
			ImGui::SameLine();
			if(ImGui::Button("Prefab"))
			{show_prefab_list = true;}
			ImGui::End();
		}

		if (show_save)
		{
			ImGui::Begin("Save as", &show_save);
			ImGui::Text("Type a save filename\n"
			"Saved to the same location as LUA.Editor.exe\n\n"
			"Or use the navigate UI to directly save to a location.\n"
			"Do not forget to add extension .txt/.lua\n\n"
			"Choose a Workspace to save.\n");
			ImGui::Separator();
			ImGui::Checkbox("Workspace #1", &save_selected_one);
			ImGui::Checkbox("Workspace #2", &save_selected_two);
			ImGui::Checkbox("Workspace #3", &save_selected_three);
			if (save_selected_one == true){save_selected_two = false;save_selected_three = false;}
			if (save_selected_two == true){save_selected_one = false;save_selected_three = false;}
			if (save_selected_three == true){save_selected_two = false;save_selected_one = false;}
			static char save_file[100] = "New_save.lua";    // setup text filtering, could be in latest update.
            string save_name = save_file;
			ImGui::Separator();
			ImGui::InputText("####save", save_file, IM_ARRAYSIZE(save_file), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll);
            ImGui::Separator();
			if(ImGui::Button("Save"))
			{
				if(save_selected_one == true){ofstream save_data(save_name.c_str());if (save_data.is_open()){save_data << Workspace1;save_data.close(); show_save_complete = true;}}
				if(save_selected_two == true){ofstream save_data(save_name.c_str());if (save_data.is_open()){save_data << Workspace2;save_data.close();show_save_complete = true;}}
				if(save_selected_three == true){ofstream save_data(save_name.c_str());if (save_data.is_open()){save_data << Workspace3;save_data.close();show_save_complete = true;}}
			}
			ImGui::SameLine();
			if(ImGui::Button("UI Open"))
			{show_guisave = true;}
			ImGui::End();
		}
		if (show_save_complete)
		{
			ImGui::Begin("###saved", &show_save_complete);
			if(ImGui::Button("SAVED",ImVec2(-1,-1))) {show_save_complete = false;}
			ImGui::End();
		}
		if (show_prefab_list)
		{
			ImGui::Begin("Prefabs", &show_prefab_list);
			ImGui::Text("Type in the selected with extension");
			ImGui::Separator();
			ImGui::Text("These are simple tests for Lua.  Some of them contain useful code.\n"
						"They are meant to be run to make sure Lua is built correctly and also\n"
						"to be read, to see how Lua programs look.\n"
						"Here is a one-line summary of each program:\n\n");

			ImGui::Text("bisect.lua");ImGui::SameLine(200);ImGui::Text("bisection method for solving non-linear equations");
   			ImGui::Text("cf.lua");ImGui::SameLine(200);ImGui::Text("temperature conversion table (celsius to farenheit)");
   			ImGui::Text("echo.lua");ImGui::SameLine(200);ImGui::Text("echo command line arguments");
   			ImGui::Text("env.lua");ImGui::SameLine(200);ImGui::Text("environment variables as automatic global variables");
   			ImGui::Text("factorial.lua");ImGui::SameLine(200);ImGui::Text("factorial without recursion");
   			ImGui::Text("fib.lua");ImGui::SameLine(200);ImGui::Text("fibonacci function with cache");
   			ImGui::Text("fibfor.lua");ImGui::SameLine(200);ImGui::Text("fibonacci numbers with coroutines and generators");
   			ImGui::Text("globals.lua");ImGui::SameLine(200);ImGui::Text("report global variable usage");
   			ImGui::Text("hello.lua");ImGui::SameLine(200);ImGui::Text("the first program in every language");
   			ImGui::Text("life.lua");ImGui::SameLine(200);ImGui::Text("Conways Game of Life");
   			ImGui::Text("luac.lua");ImGui::SameLine(200);ImGui::Text("bare-bones luac");
   			ImGui::Text("printf.lua");ImGui::SameLine(200);ImGui::Text("an implementation of printf");
   			ImGui::Text("readonly.lua");ImGui::SameLine(200);ImGui::Text("make global variables readonly");
   			ImGui::Text("sieve.lua");ImGui::SameLine(200);ImGui::Text("the sieve of of Eratosthenes programmed with coroutines");
   			ImGui::Text("sort.lua");ImGui::SameLine(200);ImGui::Text("two implementations of a sort function");
   			ImGui::Text("table.lua");ImGui::SameLine(200);ImGui::Text("make table, grouping all data for the same item");
   			ImGui::Text("trace-calls.lua");ImGui::SameLine(200);ImGui::Text("trace calls");
   			ImGui::Text("trace-globals.lua");ImGui::SameLine(200);ImGui::Text("trace assigments to global variables");
   			ImGui::Text("undefined.lua");ImGui::SameLine(200);ImGui::Text("catch \"undefined\" global variables");
   			ImGui::Text("xd.lua");ImGui::SameLine(200);ImGui::Text("hex dump");
			ImGui::End();
		}
		if (show_IO)
		{
			ImGui::Begin("Output options", &show_IO);
			ImGui::Text("Type in the selected fields.\n"
						"To alter the output options then update batch.\n\n"
						"Once the batch file is made, you then only change the directories\n"
						"When you change working folders. Otherwise options are kept in batch.\n\n"
						"Default directory is the same location of LUA.Editor\n\n"
						"No blank spaces & special characters.\n"
						"Run 'Batch' from Editor tools.\n\n"
						"Batch uses a wildcard and will move all .lua/.out");
			ImGui::Separator();
			static char save_Output_saved[1024] = "C:\\%DIR%";    // setup text filtering, could be in latest update.
            string saved_lua_Output = save_Output_saved;
			ImGui::Text("Output script save folder - Where you wish the .lua scripts to be moved to.");
			ImGui::InputText("###save_Output_saved", save_Output_saved, IM_ARRAYSIZE(save_Output_saved), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll);
            ImGui::SameLine();
            ImGui::Button("Save");
			ImGui::Separator();
			static char save_Output_complation[1024] = "C:\\%DIR%";    // setup text filtering, could be in latest update.
            string save_Output_compiler = save_Output_complation;
			ImGui::Text("Compiler output folder - Where you wish the .out scripts to be moved to.");
			ImGui::InputText("###save_Output_complation", save_Output_complation, IM_ARRAYSIZE(save_Output_complation), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll);
            ImGui::SameLine();
            ImGui::Button("Save");
			ImGui::Separator();
			if(ImGui::Button("Update batch"))
			{
				ofstream save_data("Copy.bat");
				if (save_data.is_open())
				{
				save_data << luaDIR;
				save_data << saved_lua_Output;
				save_data << '\n';
				save_data << outDIR;
				save_data << save_Output_compiler;
				save_data.close();
				show_save_complete = true;}
			}
			ImGui::End();
		}
		if (show_options)
		{
			ImGui::Begin("Settings", &show_options);
			ImGui::ShowStyleEditor();
			ImGui::ShowMetricsWindow();
			ImGui::End();
		}
		if (show_about_editor)
		{
			ImGui::Begin("About", &show_about_editor);
            ImGui::Text("");
            ImGui::Text("Dear ImGui, %s", ImGui::GetVersion());
            ImGui::Text("By Omar Cornut and all dear imgui contributors.");
        	ImGui::Text("Dear ImGui is licensed under the MIT License, see LICENSE for more information.");
        	ImGui::Text("");
			ImGui::Text("LUA Editor by Luke Hays");
            ImGui::Text("");
			ImGui::Text("Written in C++, using Dev ++ with the TDM Mingw64 compiler.");
            ImGui::Text("Useing IMGUI API.");
            ImGui::Text("Built for the purpose of making & testing scripts much easier.\n"
						"Was using Notepad ++, while good still lacked functionality.\n"
						"So this program was born.\n\n");
            ImGui::End();
        }
        if(show_help_support)
		{
			ImGui::Begin("Help & Support", &show_help_support,ImGuiWindowFlags_AlwaysHorizontalScrollbar);
			ImGui::Text("LUA.Editor\n\n"
			"Usage :- \n"
			"Simply save a workspace to compile or run.\n\n");
			ImGui::Separator();
			ImGui::Text("LUA interpreter\n\n"
						"Type in compiler console 'lua filename.lua' to test a script.\n\n");
			ImGui::Text("lua is the stand-alone Lua interpreter. It loads and executes Lua programs, either in textual source form or in precompiled binary form.\n"
			"(Precompiled binaries are output by luac, the Lua compiler.) lua can be used as a batch interpreter and also interactively.\n\n"
			"The given options (see below) are executed and then the Lua program in file script is loaded and executed. The given args are available to script as strings in a global table named arg.\n"
			"If these arguments contain spaces or other characters special to the shell, then they should be quoted (but note that the quotes will be removed by the shell).\n"
			"The arguments in arg start at 0, which contains the string `script'. The index of the last argument is stored in \" arg.n \". The arguments given in the command line before script, including the name of the interpreter, are available in negative indices in arg.\n\n"
			"At the very start, before even handling the command line, lua executes the contents of the environment variable LUA_INIT, if it is defined. If the value of LUA_INIT is of the form `@filename', then filename is executed. Otherwise, the string is assumed to be a Lua statement and is executed.\n\n"
			"Options start with - and are described below. You can use \"--\" to signal the end of options.\n\n"
			"If no arguments are given, then \"-v -i\" is assumed when the standard input is a terminal; otherwise, \"-\" is assumed.\n\n"
			"In interactive mode, lua prompts the user, reads lines from the standard input, and executes them as they are read. If a line does not contain a complete statement, then a secondary prompt is displayed and lines are read until a complete statement is formed or a syntax error is found.\n"
			"So, one way to interrupt the reading of an incomplete statement is to force a syntax error: adding a `;' in the middle of a statement is a sure way of forcing a syntax error (except inside multiline strings and comments; these must be closed explicitly).\n"
			"If a line starts with `=', then lua displays the values of all the expressions in the remainder of the line. The expressions must be separated by commas. The primary prompt is the value of the global variable _PROMPT, if this value is a string; otherwise, the default prompt is used.\n"
			"Similarly, the secondary prompt is the value of the global variable _PROMPT2. So, to change the prompts, set the corresponding variable to a string of your choice. You can do that after calling the interpreter or on the command line with \"_PROMPT\" \"=\'lua: \'\", for example.\n"
			"(Note the need for quotes, because the string contains a space.) The default prompts are ``> '' and ``>> ''.\" \n\n"
			"OPTIONS\n\n"
			" - load and execute the standard input as a file, that is, not interactively, even when the standard input is a terminal.\n\n"
			"-e \"stat\" execute statement stat. You need to quote stat if it contains spaces, quotes, or other characters special to the shell.\n\n"
			"-i enter interactive mode after script is executed.\n\n"
			"-l \"file\" call require( file) before executing script. Typically used to load libraries (hence the letter l).\n\n"
			"-v show version information.\n\n");
			ImGui::Text("SYNOPSIS\n\n"
						"lua [ options ] [ script [ args ] ]");
			ImGui::Separator();
			ImGui::Text("To use simply type 'luac' in the compiler console.\n\n");
			ImGui::Text("LUAC Compiler\n\n");
			ImGui::Text("luac is the Lua compiler. It translates programs written in the Lua programming language into binary files that can be latter loaded and executed.\n\n"
						"The main advantages of precompiling chunks are: faster loading, protecting source code from user changes, and off-line syntax checking.\n\n"
						"Pre-compiling does not imply faster execution because in Lua chunks are always compiled into bytecodes before being executed. luac simply allows those bytecodes to be saved in a file for later execution.\n\n"
						"luac produces a single output file containing the bytecodes for all source files given. By default, the output file is named luac.out, but you can change this with the -o option.\n\n"
						"The binary files created by luac are portable to all architectures with the same word size. This means that binary files created on a 32-bit platform (such as Intel) can be read without change in another 32-bit platform (such as Sparc),\n"
						"even if the byte order (``endianness'') is different. On the other hand, binary files created on a 16-bit platform cannot be read in a 32-bit platform, nor vice-versa.\n\n"
						"In the command line, you can mix text files containing Lua source and binary files containing precompiled chunks. This is useful to combine several precompiled chunks, even from different (but compatible) platforms, into a single precompiled chunk.\n\n"
						"You can use \"-\" to indicate the standard input as a source file and \"--\" to signal the end of options (that is, all remaining arguments will be treated as files even if they start with \"-\").\n\n"
						"The internal format of the binary files produced by luac is likely to change when a new version of Lua is released. So, save the source files of all Lua programs that you precompile.\n\n"
						"OPTIONS\n\n"
						"Options must be separate.\n\n"
						"-l produce a listing of the compiled bytecode for Lua's virtual machine. Listing bytecodes is useful to learn about Lua's virtual machine. If no files are given, then luac loads luac.out and lists its contents.\n\n"
						"-o \"file\" output to file, instead of the default luac.out. The output file may be a source file because all files are loaded before the output file is written. Be careful not to overwrite precious files.\n\n"
						"-p load files but do not generate any output file. Used mainly for syntax checking and for testing precompiled chunks: corrupted files will probably generate errors when loaded.\n"
						"Lua always performs a thorough integrity test on precompiled chunks. Bytecode that passes this test is completely safe, in the sense that it will not break the interpreter. However, there is no guarantee that such code does anything sensible.\n"
						"(None can be given, because the halting problem is unsolvable.) If no files are given, then luac loads luac.out and tests its contents. No messages are displayed if the file passes the integrity test.\n\n"
						"-s strip debug information before writing the output file. This saves some space in very large chunks, but if errors occur when running these chunks, then the error messages may not contain the full information they usually do (line numbers and names of locals are lost).\n\n"
						"-v show version information.\n\n");
			ImGui::Text("SYNOPSIS\n\n"
					"luac [ options ] [ filenames ]");
			ImGui::End();
		}
///////////////////////////////////////////////////////////////////////////
//
//	WIP ui open/save file explorer using boost file system.
//	Should be able to add a small folder icon to represent directories.
//	Same also for .txt/.lua/.out files.
//
//
//	Nowi have a generic save/load ui to copy & paste into
//	other projects.
//
		if (show_guiopen)
		{
			ImGui::Begin("Generic open file explorer", &show_guiopen);
			ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
			ImGui::BeginChild("####leftpanel", ImVec2(50,300), true);
			ImGui::Text("");
			ImGui::Separator();
			ImGui::Separator();
			ImGui::EndChild();
			ImGui::SameLine();
			ImGui::BeginChild("####openviewer", ImVec2(-1,300), true);
			if(ImGui::ImageButton((void *)up, ImVec2(15, 15), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}
            if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Up");ImGui::EndTooltip();}
			ImGui::SameLine();
			ImGui::Text("C:\\home");
			ImGui::Separator();
			ImGui::Separator();
			ImGui::EndChild();
			ImGui::BeginChild("####bottompanel", ImVec2(300,58), true);
			ImGui::Text("");
			ImGui::PushItemWidth(-1);
			ImGui::SameLine();
			static char open_file[40] = "";
			ImGui::InputText("###open_file", open_file, IM_ARRAYSIZE(open_file), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll);
			ImGui::Text("");
			ImGui::SameLine();
////////////////////////////////////////////////////////////////////
//
//	Filters output display.
//
			static int filetype = -1;
			ImGui::Combo("####dummyme",&filetype," \0.txt\0.lua\0", 3);
			ImGui::PopItemWidth();
			ImGui::EndChild();
///////////////////////////////////////////////////////////////////
			ImGui::SameLine();
			ImGui::BeginChild("####bottompanelopen", ImVec2(-1,58), true);
			ImGui::Button("Open",ImVec2(80,40));
			ImGui::SameLine();
			ImGui::Button("Info",ImVec2(80,40));
			ImGui::EndChild();
			ImGui::PopStyleVar();
  			ImGui::End();
		}

		if (show_guisave)
		{
			ImGui::Begin("Generic save file explorer", &show_guisave);
			ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
			ImGui::BeginChild("####leftpanel", ImVec2(50,300), true);
			ImGui::Text("");
			ImGui::Separator();
			ImGui::Separator();
			ImGui::EndChild();
			ImGui::SameLine();
			ImGui::BeginChild("####openviewer", ImVec2(-1,300), true);
			if(ImGui::ImageButton((void *)up, ImVec2(15, 15), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}
            if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Up");ImGui::EndTooltip();}
			ImGui::SameLine();
			ImGui::Text("C:\\home");
			ImGui::Separator();
			ImGui::Separator();
			ImGui::EndChild();
			ImGui::BeginChild("####bottompanel", ImVec2(300,58), true);
			ImGui::Text("");
			ImGui::PushItemWidth(-1);
			ImGui::SameLine();
			static char open_file[40] = "";
			ImGui::InputText("###save_file", open_file, IM_ARRAYSIZE(open_file), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll);
			ImGui::Text("");
			ImGui::SameLine();
//////////////////////////////////////////////////////////////////////
//
//	Save type.
//
			static int filetype = -1;
			ImGui::Combo("####dummyme",&filetype," \0.txt\0.lua\0", 3);
			ImGui::PopItemWidth();
			ImGui::EndChild();
//////////////////////////////////////////////////////////////////////
			ImGui::SameLine();
			ImGui::BeginChild("####bottompanelopen", ImVec2(-1,58), true);
			ImGui::Button("Save",ImVec2(80,40));
			ImGui::SameLine();
			ImGui::Button("Info",ImVec2(80,40));
			ImGui::EndChild();
			ImGui::PopStyleVar();
  			ImGui::End();
		}
////////////////////////////////////////////////////////////////////////
//
//	Web browser - WIP -Skeleton-
//
//
//	Oh boy the loverly code, I need to save this.
//	Itching so badly to write a server app =)
//
if (show_web_browser)
		{
			show_inprogram_dbg	= true;
			ImGui::Begin("WIP *Skeleton* Minimal web browser", &show_web_browser);
			ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
            ImGui::BeginChild("####webmenu", ImVec2(-1,35), true,ImGuiWindowFlags_NoScrollbar);

			if(ImGui::ImageButton((void *)home, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}
            if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Home");ImGui::EndTooltip();}

			ImGui::SameLine();
			if(ImGui::ImageButton((void *)back, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}
            if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Back");ImGui::EndTooltip();}

			ImGui::SameLine();
			if(ImGui::ImageButton((void *)stop, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}
            if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Stop");ImGui::EndTooltip();}

			ImGui::SameLine();
			if(ImGui::ImageButton((void *)forward, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}
            if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Forward");ImGui::EndTooltip();}

			ImGui::SameLine();
			ImGui::PushItemWidth(300);
			static char web_url[1024] = "www.google.com";
			ImGui::InputText("###url_address", web_url, IM_ARRAYSIZE(web_url), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_EnterReturnsTrue);
			ImGui::PopItemWidth();

			ImGui::SameLine();
			if(ImGui::ImageButton((void *)web, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255)))

			{

			}

			if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Go/Refresh");ImGui::EndTooltip();}

			ImGui::SameLine();
			if(ImGui::ImageButton((void *)bookmarks, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){show_bookmarks_saved = true;}
            if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Bookmarks");ImGui::EndTooltip();}

			ImGui::SameLine();
			if(ImGui::ImageButton((void *)downloads, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){show_download_manager = true;}
            if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Downloads & Uploads");ImGui::EndTooltip();}

			ImGui::SameLine();
			if(ImGui::ImageButton((void *)settings, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){show_web_settings = true;}
            if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Browser settings");ImGui::EndTooltip();}

			ImGui::EndChild();

            ImGui::BeginChild("####web_page_display", ImVec2(-1,400), true,ImGuiWindowFlags_NoScrollbar);

			ImGui::EndChild();
			ImGui::Separator();
			char buf[128];
    		sprintf(buf, "Status : %c", "|/-\\"[(int)(ImGui::GetTime()/0.25f)&3], ImGui::GetFrameCount());
    		ImGui::Text(buf);
			ImGui::SameLine(ImGui::GetWindowContentRegionWidth()/2 +350);
			if(status_empty){if(ImGui::ImageButton((void *)statusempty, ImVec2(16, 16), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}}
			if(status_red){if(ImGui::ImageButton((void *)statusred, ImVec2(16, 16), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}}
			if(status_yellow){if(ImGui::ImageButton((void *)statusyellow, ImVec2(16, 16), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}}
			if(status_green){if(ImGui::ImageButton((void *)statusgreen, ImVec2(16, 16), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}}
			if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Status - Click for details.");ImGui::EndTooltip();}

//////////////////////////////////////////////////////////
//
//	Used for tcp/ip checking connectivity.
//	Will be broken down and removed.
//	Useful for copy/paste.
//
//
			if(status_empty){status_yellow = false;status_green = false;status_red = false;}
			if(status_red){status_yellow = false;status_green = false;status_empty = false;}
			if(status_yellow){status_red = false;status_green = false;status_empty = false;}
			if(status_green){status_yellow = false;status_red = false;status_empty = false;}

/////////////////////////////////////////////////////////

			ImGui::PopStyleVar();
			ImGui::End();
		}

if(show_web_settings)
		{
			ImGui::Begin("Browser settings", &show_web_settings, ImGuiWindowFlags_MenuBar);
				if (ImGui::BeginMenuBar())
				{
				if (ImGui::BeginMenu("Options"))
				{

		    		if (ImGui::MenuItem("  Save", NULL)){}
		    		if (ImGui::MenuItem("  Import", NULL)){}
		    		ImGui::MenuItem("  Export", NULL);
		    		ImGui::MenuItem("  Default", NULL);

		    		ImGui::EndMenu();
					}
				ImGui::EndMenuBar();
				}
			ImGui::Text("Settings for browser.\nClick on the headers for details.\nClick menu options to save.");
			ImGui::Text("");
//////////////////////////////////////////////////////////////
//
//	Helpful batch file calls.
//
			if (ImGui::CollapsingHeader("TCP/IP"))
            {

			if(ImGui::Button("TCP::IP -I"))
			{
				static ImGuiOnceUponAFrame Ipstatus;
				if (Ipstatus)
					{
						boost::thread_group threads;
						threads.create_thread(ipconfigure_bat);
					}
			}
			ImGui::SameLine();
			if(ImGui::Button("Netstat On"))
			{
				static ImGuiOnceUponAFrame Ipstatus;
				if (Ipstatus)
					{
						boost::thread_group threads;
						threads.create_thread(ipconfigure_netstat_on_bat);
					}
			}
			ImGui::SameLine();
			if(ImGui::Button("Netstat -A"))
			{
				static ImGuiOnceUponAFrame Ipstatus;
				if (Ipstatus)
					{
						boost::thread_group threads;
						threads.create_thread(ipconfigure_netstat_a_bat);
					}
			}

			if(ImGui::Button("Netstat -O"))
			{
				static ImGuiOnceUponAFrame Ipstatus;
				if (Ipstatus)
					{
						boost::thread_group threads;
						threads.create_thread(ipconfigure_netstat_o_bat);

					}
			}
			ImGui::SameLine();
			if(ImGui::Button("Netstat -T"))
			{
				static ImGuiOnceUponAFrame Ipstatus;
				if (Ipstatus)
					{
						boost::thread_group threads;
						threads.create_thread(ipconfigure_netstat_t_bat);

					}
			}
			ImGui::SameLine();
			if(ImGui::Button("Netstat -F"))
			{
				static ImGuiOnceUponAFrame Ipstatus;
				if (Ipstatus)
					{
						boost::thread_group threads;
						threads.create_thread(ipconfigure_netstat_f_bat);

					}
			}
			}
			ImGui::Separator();
			if (ImGui::CollapsingHeader("WMIC"))
			{

			if(ImGui::Button("WMIC Open"))
			{
				static ImGuiOnceUponAFrame Ipstatus1;
				if (Ipstatus1)
					{
						boost::thread_group threads;
						threads.create_thread(ipconfigure_wmic_bat);
					}
			}
			ImGui::SameLine();
			if(ImGui::Button("WMIC - Support & Information"))
			{
				static ImGuiOnceUponAFrame Ipstatus;
				if (Ipstatus)
					{
						boost::thread_group threads;
						threads.create_thread(ipconfigure_wmic_help_bat);

					}
			}
			}
////////////////////////////////////////////////////////////////
			ImGui::Separator();
			if (ImGui::CollapsingHeader("Browser options"))
			{
			ImGui::Text("");
			ImGui::Text("Mobile phone or Desktop browsing:");
			ImGui::Checkbox("Mobile only", &mobile_html);
			ImGui::Separator();
			ImGui::Text("Bookmarks:");
			ImGui::BeginChild("####bookmarks", ImVec2(-1,150), true,ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse);
			ImGui::InputTextMultiline("##bookmarks_kept", bookmarks_kept, IM_ARRAYSIZE(bookmarks_kept), ImVec2(-1.0f, -1.0 * 16), ImGuiInputTextFlags_AllowTabInput);
			if(ImGui::SmallButton("Update bookmarks")){ofstream save_data("Bookmarks.setting");if (save_data.is_open()){save_data << bookmarks_kept;save_data.close(); show_save_complete = true;}}
			if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Update to save bookmarks.");ImGui::EndTooltip();}
			ImGui::EndChild();
			ImGui::PushItemWidth(-1);
			ImGui::Separator();
			ImGui::Text("Homepage:");
			static char homepage[256] = "www.google.com";
			ImGui::InputText("###default_homepage", homepage, IM_ARRAYSIZE(homepage), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll);
			ImGui::Separator();
			ImGui::Text("Downloads folder:");
			static char download_folder[256] = "C:\\";
			ImGui::InputText("###default_download", download_folder, IM_ARRAYSIZE(download_folder), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll);
			ImGui::PopItemWidth();
			}

			ImGui::Separator();
			if (ImGui::CollapsingHeader("FTP"))
            {
            ImGui::PushItemWidth(-1);
			ImGui::Text("");
			ImGui::Text("FTP Settings:");
			ImGui::Text("");
			ImGui::Text("IP:PORT");
			static char ftpconnect[256] = "192.168.0.1:1000";
			ImGui::InputText("###default_ftpip", ftpconnect, IM_ARRAYSIZE(ftpconnect), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll);
			ImGui::Text("");
			ImGui::Text("Login details:");
			static char ftp_connect_name[256] = "Username";
			ImGui::InputText("###default_ftp_name", ftp_connect_name, IM_ARRAYSIZE(ftp_connect_name), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll);
			static char ftp_connect_password[256] = "Password";
			ImGui::InputText("###default_ftp_password", ftp_connect_password, IM_ARRAYSIZE(ftp_connect_password), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_Password);
			ImGui::Checkbox("Save FTP Login credentials", &save_ftp_login);
			ImGui::Text("");
			ImGui::Text("FTP Connection test. ");
			ImGui::SameLine();
			ImGui::SmallButton("Test");
			ImGui::PopItemWidth();
			}
			ImGui::Separator();
			if (ImGui::CollapsingHeader("Cloud Settings"))
			{
			ImGui::PushItemWidth(-1);
			ImGui::Text("");
			ImGui::Text("Cloud Settings:");
			ImGui::Text("");
			ImGui::Text("Web address:");
			static char cloudconnect[256] = "www.google.com/cloud";
			ImGui::InputText("###default_cloudaddress", cloudconnect, IM_ARRAYSIZE(cloudconnect), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll);
			ImGui::Text("");
			ImGui::Text("Login details:");
			static char cloud_connect_name[256] = "Username";
			ImGui::InputText("###default_cloud_name", cloud_connect_name, IM_ARRAYSIZE(cloud_connect_name), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll);
			static char cloud_connect_password[256] = "Password";
			ImGui::InputText("###default_cloud_password", cloud_connect_password, IM_ARRAYSIZE(cloud_connect_password), ImGuiInputTextFlags_CharsNoBlank | ImGuiInputTextFlags_AutoSelectAll | ImGuiInputTextFlags_Password);
			ImGui::Checkbox("Save Cloud Login credentials", &save_cloud_login);
			ImGui::Text("");
			ImGui::Text("Cloud Connection test. ");
			ImGui::SameLine();
			ImGui::SmallButton("Test");
			ImGui::PopItemWidth();
			}
			ImGui::Separator();
			ImGui::End();
		}
/////////////////////////////////////////////////////////////////
//
//	Downloads manager.
//
//	Handles upstream/downstream.
//
if (show_download_manager)
	{
		ImGui::Begin("Downloads & Uploads Manager", &show_download_manager);
		ImGui::Text("Download");
		ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
		ImGui::BeginChild("####Downloading", ImVec2(-1,135), true);
		ImGui::Text("Filename: ");
		ImGui::Separator();
		ImGui::Text("Host:");
		ImGui::Separator();
		static float Download_rate = 0.0f;
		ImGui::Text("Transfer:  %fKb/s",Download_rate);
		ImGui::Separator();
		static float Download = 0.0f;
		ImGui::ProgressBar(Download, ImVec2(-1.0f,0.0f));
		ImGui::Separator();
		if(ImGui::ImageButton((void *)resume, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}
        if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Continue");ImGui::EndTooltip();}

		ImGui::SameLine();
		if(ImGui::ImageButton((void *)pause, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}
        if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Pause");ImGui::EndTooltip();}

		ImGui::SameLine();
		if(ImGui::ImageButton((void *)stop, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}
        if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Cancel");ImGui::EndTooltip();}

		ImGui::SameLine();
		ImGui::Button("FTP Download");

		ImGui::EndChild();
		ImGui::PopStyleVar();
		ImGui::Text("Upload");
		ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
		ImGui::BeginChild("####Uploading", ImVec2(-1,135), true);
		ImGui::Text("Filename: ");
		ImGui::Separator();
		ImGui::Text("Upload location:");
		ImGui::Separator();
		static float Upload_rate = 0.0f;
		ImGui::Text("Transfer:  %fKb/s",Upload_rate);
		ImGui::Separator();
		static float Upload = 0.0f;
		ImGui::ProgressBar(Upload, ImVec2(-1.0f,0.0f));
		ImGui::Separator();
		if(ImGui::ImageButton((void *)resume, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}
        if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Continue");ImGui::EndTooltip();}

		ImGui::SameLine();
		if(ImGui::ImageButton((void *)pause, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}
        if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Pause");ImGui::EndTooltip();}

		ImGui::SameLine();
		if(ImGui::ImageButton((void *)stop, ImVec2(20, 20), ImVec2(0,0),ImVec2(1,1),0,ImVec4(0,0,0,0),ImVec4(255,255,255,255))){}
        if (ImGui::IsItemHovered()){ImGui::BeginTooltip();ImGui::Text("Cancel");ImGui::EndTooltip();}

		ImGui::SameLine();
		ImGui::Button("FTP Upload");

		ImGui::EndChild();
		ImGui::PopStyleVar();
		ImGui::End();
	}
//////////////////////////////////////////////////////////////
//
//	Bookmarks select.
//
//	Will used selected to seek.get(0,"url list location");
//	E.G :-
//
//	if seleced is left clicked
//	seek.get(0,i); https://github.com/ (1 from 0 - 2 - currently)
//
//	Load into buffer, pass buffer to resolver.
//	Bookmark page loaded, url in textinput changed
//	to reflect bookmark selected.
//
//	If selected is blank do nothing?.
//
if(show_bookmarks_saved)
	{

		ImGui::Begin("Bookmarks", &show_bookmarks_saved);
		char Bookmark_display[1024*16];
		ifstream file("Bookmarks.setting", ios::in|ios::ate);
			if (file.is_open())
				{
				streampos size;
		  		size = file.tellg();
				file.seekg (0, ios::beg);
				for (int w = 0; w < size; w++)
				{
				file.getline(Bookmark_display, size);
				int i = -1;
				bool selected;
				char buf[32];
				sprintf(buf, "%s", Bookmark_display);
			    if (ImGui::Selectable(buf, selected == i))
				selected = i;
				}
				file.close();
				}

		ImGui::End();
	}
/////////////////////////////////////////////////////////////////////
//
//	Debugger.
//
//	Temp, while code under construction.
//
if(show_inprogram_dbg)
		{
			ImGui::Begin("Debugger", &show_inprogram_dbg);
			ImGui::Checkbox("red",&status_red);
			ImGui::Checkbox("yellow",&status_yellow);
			ImGui::Checkbox("green",&status_green);
			ImGui::Checkbox("empty",&status_empty);

			ImGui::End();
		}
/////////////////////////////////////////////////////////////////

////////////////////////////////////////////////////////////////////////
//
// Rendering.
//
///////////////////////////////////////////////////////////
        ImGui::EndFrame();
        g_pd3dDevice->SetRenderState(D3DRS_ZENABLE, false);
        g_pd3dDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, false);
        g_pd3dDevice->SetRenderState(D3DRS_SCISSORTESTENABLE, false);
        D3DCOLOR clear_col_dx = D3DCOLOR_RGBA((int)(clear_color.x*255.0f), (int)(clear_color.y*255.0f), (int)(clear_color.z*255.0f), (int)(clear_color.w*255.0f));
        g_pd3dDevice->Clear(0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, clear_col_dx, 1.0f, 0);
        if (g_pd3dDevice->BeginScene() >= 0)
        {
            ImGui::Render();
            g_pd3dDevice->EndScene();
        }
        HRESULT result = g_pd3dDevice->Present(NULL, NULL, NULL, NULL);

        // Handle loss of D3D9 device
        if (result == D3DERR_DEVICELOST && g_pd3dDevice->TestCooperativeLevel() == D3DERR_DEVICENOTRESET)
        {
            ImGui_ImplDX9_InvalidateDeviceObjects();
            g_pd3dDevice->Reset(&g_d3dpp);
            ImGui_ImplDX9_CreateDeviceObjects();
        }
    }
	Shutdown:
    ImGui_ImplDX9_Shutdown();
    if (g_pd3dDevice) g_pd3dDevice->Release();
    if (pD3D) pD3D->Release();
    UnregisterClass(_T("ImGui Example"), wc.hInstance);

    return 0;
}


text:
// Andrew Naplavkov

#ifndef BARK_DB_PROVIDER_HPP
#define BARK_DB_PROVIDER_HPP

#include <bark/db/command.hpp>
#include <bark/db/detail/meta_ops.hpp>
#include <bark/db/fwd.hpp>
#include <bark/detail/lru_cache.hpp>
#include <bark/geometry/geometry.hpp>
#include <boost/range/adaptor/filtered.hpp>
#include <boost/range/combine.hpp>
#include <map>

namespace bark::db {

using busy_exception = lru_cache::busy_exception;

/// Thread-safe, caching interface for spatial data source
struct provider {
    virtual ~provider() = default;

    /// Returns layers in this data source
    virtual std::map<qualified_name, meta::layer_type> dir() = 0;

    /// Returns PROJ.4 string for the spatial reference system
    virtual std::string projection(const qualified_name& layer) = 0;

    /// Returns the minimum bounding rectangle of the data set
    virtual geometry::box extent(const qualified_name& layer) = 0;

    /// Changes the pixel to undistort the raster
    virtual geometry::box undistorted_pixel(const qualified_name& layer,
                                            const geometry::box& pixel) = 0;

    /// Returns a balanced data grid.

    /// @param layer is a data set identifier;
    /// @param extent is a spatial filter;
    /// @param pixel selects the level of the raster pyramid.
    virtual geometry::multi_box tile_coverage(const qualified_name& layer,
                                              const geometry::box& extent,
                                              const geometry::box& pixel) = 0;

    /// Returns @ref rowset with spatial data set.

    /// Columns @code GEOMETRY[,IMAGE][,ATTRIBUTES...] @endcode
    /// @param layer is a data set identifier;
    /// @param extent is a spatial filter;
    /// @param pixel selects the level of the raster pyramid.
    virtual rowset spatial_objects(const qualified_name& layer,
                                   const geometry::box& extent,
                                   const geometry::box& pixel) = 0;

    /// Returns SQL command interface
    virtual command_holder make_command() = 0;

    /// Describes table
    virtual meta::table table(const qualified_name& tbl_nm) = 0;

    /// Returns name and DDL command to create a table
    virtual std::pair<qualified_name, std::string> ddl(const meta::table&) = 0;

    /// Outputs SQL LIMIT clause
    virtual void page_clause(sql_builder&, size_t offset, size_t limit) = 0;

    /// Resets LRU cache
    virtual void refresh() = 0;
};

inline bool queryable(provider& pvd)
try {
    pvd.make_command();
    return true;
}
catch (const std::exception&) {
    return false;
}

inline sql_builder builder(provider& pvd)
{
    return builder(*pvd.make_command());
}

template <class Sql>
void exec(provider& pvd, Sql&& sql)
{
    exec(*pvd.make_command(), std::forward<Sql>(sql));
}

template <class Sql>
rowset fetch_all(provider& pvd, Sql&& sql)
{
    auto cmd = pvd.make_command();
    exec(*cmd, std::forward<Sql>(sql));
    return fetch_all(*cmd);
}

inline sql_builder select_sql(provider& pvd,
                              const qualified_name& tbl_nm,
                              size_t offset,
                              size_t limit)
{
    auto res = builder(pvd);
    auto tbl = pvd.table(tbl_nm);
    auto pri =
        boost::range::find_if(tbl.indexes, same{meta::index_type::Primary});
    res << "SELECT " << list{tbl.columns, ", ", decode} << " FROM " << tbl_nm
        << " ORDER BY "
        << list{pri != tbl.indexes.end()
                    ? pri->columns
                    : names(tbl.columns | boost::adaptors::filtered(sortable)),
                ", ",
                id<>}
        << " ";
    pvd.page_clause(res, offset, limit);
    return res;
}

template <class ColumnNames, class Rows>
sql_builder insert_sql(provider& pvd,
                       const qualified_name& tbl_nm,
                       const ColumnNames& col_nms,
                       const Rows& rows)
{
    auto tbl = pvd.table(tbl_nm);
    auto cols = as<std::vector<meta::column>>(col_nms, [&](const auto& col_nm) {
        return *db::find(tbl.columns, col_nm);
    });
    auto encode = [&](const auto& row) {
        return streamable([&](sql_builder& bld) {
            bld << "("
                << list{boost::combine(cols, row),
                        ",",
                        [](const auto& pair) {
                            return db::encode(boost::get<0>(pair),
                                              boost::get<1>(pair));
                        }}
                << ")";
        });
    };

    auto res = builder(pvd);
    res << "INSERT INTO " << tbl_nm << " (" << list{col_nms, ", ", id<>}
        << ") VALUES\n"
        << list{rows, ",\n", encode};
    return res;
};

inline sql_builder insert_sql(provider& pvd,
                              const qualified_name& tbl_nm,
                              const rowset& rows)
{
    return insert_sql(pvd, tbl_nm, rows.columns, select(rows));
}

inline sql_builder drop_sql(provider& pvd, const qualified_name& tbl_nm)
{
    auto res = builder(pvd);
    res << "DROP TABLE " << tbl_nm;
    return res;
}

inline meta::column column(provider& pvd, const qualified_name& col_nm)
{
    return *find(pvd.table(qualifier(col_nm)).columns, col_nm.back());
}

}  // namespace bark::db

#endif  // BARK_DB_PROVIDER_HPP

max_stars_repo_name: storm-ptr/bark

max_issues_repo_name: storm-ptr/bark

max_forks_repo_name: storm-ptr/bark