<commit_before>/*
 * Copyright (c) 2013-2014, Muhammad Shahzad Shafi <shahzad at voip-demos dot com>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted per Mozilla Public License v2.0.
 *
 * 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 OWNER 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 "itv_config.h"

int use_char_itv(std::string data) {
	ITV_ASCII *caller = new ITV_ASCII();
	caller->load(48, 57);
	caller->load(65, 90);
	caller->load(97, 122);

	std::string str = ""; //"!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

	//cout << "Sender ITV Table before initialization: " << endl << caller->to_string() << endl;
	std::string enc = caller->encode(str);
	//cout << "Sender ITV Table after initialization: " << endl << caller->to_string() << endl;

	//caller->write("/tmp/callee.txt");

	std::string key = caller->dump(':');
	enc = caller->encode(data);

	//ITV_ASCII *callee = new ITV_ASCII();
	//callee->read("/tmp/callee.txt");

	cout << "Key: " << key << endl;
	ITV_ASCII *callee = new ITV_ASCII(key);

	//cout << "Receiver ITV Table after initialization: " << endl << callee->to_string() << endl;
	std::string dcr = callee->decode(enc);

	cout << "Plaintext: " << data << endl;
	cout << "Encrypted Text: " << enc << endl;
	cout << "Decrypted Text: " << dcr << endl;
	cout << endl;

	return 0;
};

int use_word_itv(std::string data) {
	ITV_Words *caller = new ITV_Words("./wordsEn.txt", 0);

	std::string str = "a quick brown fox jumps over the lazy dog";
	std::string enc = caller->encode(str);

	caller->write("/tmp/caller.txt");
	//size_t enc_size = caller->get_expected_length(str, 0);
	enc = caller->encode(data);

	ITV_Words *callee = new ITV_Words("/tmp/caller.txt", 0);
	//size_t dcr_size = callee->get_expected_length(enc, 1);
	std::string dcr = callee->decode(enc);

	cout << "Plaintext: " << data << endl;
	cout << "Encrypted Text: " << enc << endl;
	cout << "Decrypted Text: " << dcr << endl;
	//cout << "Expected size of encrypted text: " << enc_size << endl;
	//cout << "Actual size of encrypted text: " << enc.length() << endl;
	//cout << "Expected size of decrypted text: " << dcr_size << endl;
	//cout << "Actual size of decrypted text: " << dcr.length() << endl;
	cout << endl;

	return 0;
};

int main() {
	std::string str = "a quick brown fox jumps over the lazy dog.";

	use_char_itv(str);
	use_word_itv(str);

	std::string def = compress(str, 1);
	std::string inf = decompress(def, 1);
	cout << "Compressed Text: " << def << endl;
	cout << "Decompressed Text: " << inf << endl;
	cout << endl;

	//cout << "Enter data to encrypt: ";
	//getline(cin, str);

	//cout << endl << endl;
	//use_char_itv(str);
	//use_word_itv(str);

	return 0;
};

<commit_msg>fixed a couple typos in last commit<commit_after>/*
 * Copyright (c) 2013-2014, Muhammad Shahzad Shafi <shahzad at voip-demos dot com>
 *
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted per Mozilla Public License v2.0.
 *
 * 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 OWNER 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 "itv_config.h"

int use_char_itv(std::string data) {
	ITV_ASCII *caller = new ITV_ASCII();
	caller->load(48, 57);
	caller->load(65, 90);
	caller->load(97, 122);

	std::string str = ""; //"!\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";

	//cout << "Sender ITV Table before initialization: " << endl << caller->to_string() << endl;
	std::string enc = caller->encode(str);
	//cout << "Sender ITV Table after initialization: " << endl << caller->to_string() << endl;

	//caller->write("/tmp/callee.txt");

	std::string key = caller->dump(':');
	enc = caller->encode(data);

	//ITV_ASCII *callee = new ITV_ASCII();
	//callee->read("/tmp/callee.txt");

	cout << "Key: " << key << endl;
	ITV_ASCII *callee = new ITV_ASCII(key);

	//cout << "Receiver ITV Table after initialization: " << endl << callee->to_string() << endl;
	std::string dcr = callee->decode(enc);

	cout << "Plaintext: " << data << endl;
	cout << "Encrypted Text: " << enc << endl;
	cout << "Decrypted Text: " << dcr << endl;
	cout << endl;

	return 0;
};

int use_word_itv(std::string data) {
	ITV_Words *caller = new ITV_Words("./wordsEn.txt", 0);

	std::string str = "a quick brown fox jumps over the lazy dog";
	std::string enc = caller->encode(str);

	caller->write("/tmp/caller.txt");
	//size_t enc_size = caller->get_expected_length(str, 0);
	enc = caller->encode(data);

	ITV_Words *callee = new ITV_Words("/tmp/caller.txt", 0);
	//size_t dcr_size = callee->get_expected_length(enc, 1);
	std::string dcr = callee->decode(enc);

	cout << "Plaintext: " << data << endl;
	cout << "Encrypted Text: " << enc << endl;
	cout << "Decrypted Text: " << dcr << endl;
	//cout << "Expected size of encrypted text: " << enc_size << endl;
	//cout << "Actual size of encrypted text: " << enc.length() << endl;
	//cout << "Expected size of decrypted text: " << dcr_size << endl;
	//cout << "Actual size of decrypted text: " << dcr.length() << endl;
	cout << endl;

	return 0;
};

int main() {
	std::string str = "a quick brown fox jumps over the lazy dog.";

	use_char_itv(str);
	use_word_itv(str);

	std::string def = do_compress(str, 1);
	std::string inf = do_decompress(def, 1);
	cout << "Compressed Text: " << def << endl;
	cout << "Decompressed Text: " << inf << endl;
	cout << endl;

	//cout << "Enter data to encrypt: ";
	//getline(cin, str);

	//cout << endl << endl;
	//use_char_itv(str);
	//use_word_itv(str);

	return 0;
};

<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <string>

#include "algorithms.hpp"

#ifndef USE_SDSL_WTREE
#include "wavelet_tree.hpp"
#endif

std::string parse_input(char* input_file);  // TODO: @Zivec
void output_results(char* output_file, lb::lcp_array& LCP);

int main(int argc, char* argv[]) {
    if (argc != 3) {
        std::cout << "Usage: lcp_bwt input_file output_file\n";
        return -1;
    }

    lb::sequence T {"ananas$"};
    lb::alphabet A {T};
    lb::sequence BWT = lb::build_bwt(T);

    std::cout << BWT << "\n";

    lb::wtree WT = lb::build_wtree(BWT, A);
    lb::lcp_array LCP = lb::build_lcp(WT);
    output_results(argv[2], LCP);
}

void output_results(char* output_file, lb::lcp_array& lcp) {
    std::ofstream ofs(output_file, std::ofstream::out);
    ofs << "[";
    for (auto i = 0u; i < lcp.size(); ++i)
        ofs << lcp[i] << ((i != lcp.size() - 1) ? "," : "");
    ofs << "]\n";
    ofs.close();
}
std::string parse_input(char* input_file){
    std::string input, temp;
    std::ifstream file(input_file);

    if (!file) {
        std::cerr << "Unable to open file" <<std::endl;
        exit(1);
    }

    std::getline(file, temp); // first line

    while(!file.eof()){
        std::getline(file, temp);
        input += temp;
    }
    file.close();
    return input;
}<commit_msg>Improving main.cpp code style, reordering functions for readability<commit_after>#include <fstream>
#include <iostream>
#include <string>

#include "algorithms.hpp"

#ifndef USE_SDSL_WTREE
#include "wavelet_tree.hpp"
#endif

std::string parse_input(char* input_file);
void output_results(char* output_file, lb::lcp_array& LCP);

int main(int argc, char* argv[]) {
    if (argc != 3) {
        std::cout << "Usage: lcp_bwt input_file output_file\n";
        exit(1);
    }

    lb::sequence T {"ananas$"};
    lb::alphabet A {T};
    lb::sequence BWT = lb::build_bwt(T);

    std::cout << BWT << "\n";

    lb::wtree WT = lb::build_wtree(BWT, A);
    lb::lcp_array LCP = lb::build_lcp(WT);
    output_results(argv[2], LCP);
}

std::string parse_input(char* input_file) {
    std::string input, temp;
    std::ifstream file(input_file);

    if (!file) {
        std::cerr << "Unable to open file\n";
        exit(1);
    }

    std::getline(file, temp);  // first line
    while (!file.eof()) {
        std::getline(file, temp);
        input += temp;
    }
    file.close();
    return input;
}

void output_results(char* output_file, lb::lcp_array& lcp) {
    std::ofstream ofs(output_file, std::ofstream::out);
    ofs << "[";
    for (auto i = 0u; i < lcp.size(); ++i)
        ofs << lcp[i] << ((i != lcp.size() - 1) ? "," : "");
    ofs << "]\n";
    ofs.close();
}
<|endoftext|>


<commit_before>#include "QuickStopStepper.h"
#include <Task.h>
#include <InputDebounce.h>

#define BUTTON_DEBOUNCE_DELAY   20   // [ms]

#define DIR D1
#define STEP D2
#define LIMIT_SWITCH D6 // yellow wire
#define CAMERA_PIN D5 // green whire

#define BUFFER_STEPS 10

#define INFINITE_MOTION 100000

enum CalibrationState {
    NEEDS_CALIBRATION,
    FIND_UPPER,
    FOUND_UPPER,
    FIND_LOWER,
    FOUND_LOWER,
    MOVING_TO_ZERO,
    CALIBRATED
};

CalibrationState calibrationState = NEEDS_CALIBRATION;
long sliderDistanceSteps = 0;

// Define a stepper and the pins it will use
QuickStopStepper stepper(AccelStepper::DRIVER, STEP, DIR); // Defaults to AccelStepper::FULL4WIRE (4 pins) on 2, 3, 4, 5

TaskManager taskManager;

static InputDebounce limitSwitch; // not enabled yet, setup has to be called later

void onEnableMotor(uint32_t deltaTime);
void onDisableMotor(uint32_t deltaTime);

FunctionTask enableMotorTask(onEnableMotor, MsToTaskTime(4000));
FunctionTask disableMotorTask(onDisableMotor, MsToTaskTime(4000));

void limitSwitch_pressedCallback() {
    switch(calibrationState) {
        case FIND_UPPER:
            Serial.print("Found upper bound!!!  Position is: ");
            Serial.print(stepper.currentPosition());
            Serial.println(".  Stopping...");
            stepper.quickStop();
            calibrationState = FOUND_UPPER;
            break;
        case FIND_LOWER:
            Serial.print("Found lower bound!!!  Position is: ");
            Serial.print(stepper.currentPosition());
            Serial.println(".  Stopping...");
            stepper.quickStop();
            calibrationState = FOUND_LOWER;

            break;
        default:
            Serial.println("Oh shit, yo!  We hit an end!!");
            Serial.print("Hit at ");
            Serial.print(stepper.currentPosition());
            Serial.println(" steps ");
            Serial.print(stepper.distanceToGo());
            Serial.println(" steps was remaining....  Gonna stop, fuck this shit....");

            stepper.quickStop();
    }
}

void doNothingCallback() {}
void doNothingDurationCallback(unsigned long duration) {}

void setup()
{

    randomSeed(analogRead(0));
    Serial.begin(9600);

    // Change these to suit your stepper if you want
    stepper.setEnablePin(D8);
    stepper.setMaxSpeed(1000);
    stepper.setAcceleration(400);
    //stepper.moveTo(5500);

    limitSwitch.registerCallbacks(limitSwitch_pressedCallback, doNothingCallback, doNothingDurationCallback);
    limitSwitch.setup(LIMIT_SWITCH, BUTTON_DEBOUNCE_DELAY, InputDebounce::PIM_INT_PULL_UP_RES);

    //taskManager.StartTask(&enableMotorTask);
    //taskManager.StartTask(&disableMotorTask);

}

void loop()
{
    unsigned long now = millis();
    limitSwitch.process(now);

    switch(calibrationState) {
        case CALIBRATED:
            // If at the end of travel go to the other end
            if (stepper.distanceToGo() == 0) {
                Serial.print("Currently at: ");
                Serial.print(stepper.currentPosition());
                Serial.print(" moving to: ");

                long newPosition = random(0,sliderDistanceSteps);
                Serial.println(newPosition);
                stepper.moveTo(newPosition);

            }

            break;
        case NEEDS_CALIBRATION:
            Serial.println("Uncalibrated.  Gonna calibrate this shit....");
            stepper.moveTo(INFINITE_MOTION);
            calibrationState = FIND_UPPER;
            break;
        case FOUND_UPPER:
            if(!stepper.isRunning()) {
                Serial.print("Stopped.  Current Position: ");
                Serial.println(stepper.currentPosition());
                stepper.setCurrentPosition(0);
                stepper.moveTo(-INFINITE_MOTION);
                calibrationState = FIND_LOWER;
                Serial.println("Now looking for lower bound");
            }
            break;
        case FOUND_LOWER:
            if(!stepper.isRunning()) {
                Serial.print("Stopped.  Current Position: ");
                Serial.println(stepper.currentPosition());
                sliderDistanceSteps = abs(stepper.currentPosition()) - 2 * BUFFER_STEPS;
                Serial.print("Slider Distance is ");
                Serial.print(sliderDistanceSteps);
                Serial.println(" steps");
                stepper.setCurrentPosition(-BUFFER_STEPS);
                Serial.println("Moving to zero point...");
                stepper.moveTo(0);
                calibrationState = MOVING_TO_ZERO;
            }
            break;
        case MOVING_TO_ZERO:
            if(!stepper.isRunning()) {
                Serial.print("Stopped.  Current Position: ");
                Serial.println(stepper.currentPosition());
                Serial.print("Slider Distance is ");
                Serial.print(sliderDistanceSteps);
                Serial.println(" steps");
                Serial.println("Fully Calibrated and ready for action!");
                calibrationState = CALIBRATED;
            }
            break;
        default:
            break;
    }

    taskManager.Loop();
    stepper.run();
}

void onEnableMotor(uint32_t deltaTime) {
    stepper.enableOutputs();
    taskManager.StartTask(&disableMotorTask);
    taskManager.StopTask(&enableMotorTask);
}

void onDisableMotor(uint32_t deltaTime) {
    stepper.disableOutputs();
    taskManager.StopTask(&disableMotorTask);
    taskManager.StartTask(&enableMotorTask);
}
<commit_msg>calibration routine seems to be working<commit_after>#include "QuickStopStepper.h"
#include <Task.h>
#include <InputDebounce.h>

#define BUTTON_DEBOUNCE_DELAY   20   // [ms]

#define DIR D1
#define STEP D2
#define LIMIT_SWITCH D6 // yellow wire
#define CAMERA_PIN D5 // green whire

#define BUFFER_STEPS 10

#define INFINITE_MOTION 100000

enum CalibrationState {
    NEEDS_CALIBRATION,
    FIND_UPPER,
    FIND_LOWER,
    MOVING_TO_ZERO,
    CALIBRATED,
    EMERGENCY_STOP
};

CalibrationState calibrationState = NEEDS_CALIBRATION;
long sliderDistanceSteps = 0;

// Define a stepper and the pins it will use
QuickStopStepper stepper(AccelStepper::DRIVER, STEP, DIR); // Defaults to AccelStepper::FULL4WIRE (4 pins) on 2, 3, 4, 5

TaskManager taskManager;

static InputDebounce limitSwitch; // not enabled yet, setup has to be called later

void onEnableMotor(uint32_t deltaTime);
void onDisableMotor(uint32_t deltaTime);

FunctionTask enableMotorTask(onEnableMotor, MsToTaskTime(4000));
FunctionTask disableMotorTask(onDisableMotor, MsToTaskTime(4000));

void limitSwitch_pressedCallback() {
    switch(calibrationState) {
        case FIND_UPPER:
            Serial.print("Found upper bound!!!  Position is: ");
            Serial.print(stepper.currentPosition());
            Serial.println(".  Stopping...");
            stepper.setCurrentPosition(0);
            stepper.moveTo(-INFINITE_MOTION);
            calibrationState = FIND_LOWER;
            Serial.println("Now looking for lower bound");

            break;
        case FIND_LOWER:
            Serial.print("Found lower bound!!!  Position is: ");
            Serial.print(stepper.currentPosition());
            Serial.println(".  Stopping...");
            Serial.println(stepper.currentPosition());
            sliderDistanceSteps = abs(stepper.currentPosition()) - 2 * BUFFER_STEPS;
            Serial.print("Slider Distance is ");
            Serial.print(sliderDistanceSteps);
            Serial.println(" steps");
            stepper.setCurrentPosition(-BUFFER_STEPS);
            Serial.println("Moving to zero point...");
            stepper.moveTo(0);
            calibrationState = MOVING_TO_ZERO;

            break;
        default:
            Serial.println("Oh shit, yo!  We hit an end!!");
            Serial.print("Hit at ");
            Serial.print(stepper.currentPosition());
            Serial.println(" steps ");
            Serial.print(stepper.distanceToGo());
            Serial.println(" steps was remaining....  Gonna stop, fuck this shit....");
            calibrationState = EMERGENCY_STOP;
    }
}

void doNothingCallback() {}
void doNothingDurationCallback(unsigned long duration) {}

void setup()
{

    randomSeed(analogRead(0));
    Serial.begin(9600);

    // Change these to suit your stepper if you want
    stepper.setEnablePin(D8);
    stepper.setMaxSpeed(1000);
    stepper.setAcceleration(400);
    //stepper.moveTo(5500);

    limitSwitch.registerCallbacks(limitSwitch_pressedCallback, doNothingCallback, doNothingDurationCallback);
    limitSwitch.setup(LIMIT_SWITCH, BUTTON_DEBOUNCE_DELAY, InputDebounce::PIM_INT_PULL_UP_RES);

    //taskManager.StartTask(&enableMotorTask);
    //taskManager.StartTask(&disableMotorTask);

}

void loop()
{
    unsigned long now = millis();
    limitSwitch.process(now);

    switch(calibrationState) {
        case CALIBRATED:
            // If at the end of travel go to the other end
            if (stepper.distanceToGo() == 0) {
                Serial.print("Currently at: ");
                Serial.print(stepper.currentPosition());
                Serial.print(" moving to: ");

                long newPosition = random(0,sliderDistanceSteps);
                Serial.println(newPosition);
                stepper.moveTo(newPosition);

            }

            break;
        case NEEDS_CALIBRATION:
            Serial.println("Uncalibrated.  Gonna calibrate this shit....");
            stepper.moveTo(INFINITE_MOTION);
            calibrationState = FIND_UPPER;
            break;
        case MOVING_TO_ZERO:
            if(!stepper.isRunning()) {
                Serial.print("Stopped.  Current Position: ");
                Serial.println(stepper.currentPosition());
                Serial.print("Slider Distance is ");
                Serial.print(sliderDistanceSteps);
                Serial.println(" steps");
                Serial.println("Fully Calibrated and ready for action!");
                calibrationState = CALIBRATED;
            }
            break;
        default:
            break;
    }

    taskManager.Loop();
    if(calibrationState != EMERGENCY_STOP)
        stepper.run();
}

void onEnableMotor(uint32_t deltaTime) {
    stepper.enableOutputs();
    taskManager.StartTask(&disableMotorTask);
    taskManager.StopTask(&enableMotorTask);
}

void onDisableMotor(uint32_t deltaTime) {
    stepper.disableOutputs();
    taskManager.StopTask(&disableMotorTask);
    taskManager.StartTask(&enableMotorTask);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <ncurses.h>

using namespace std;

void print_menu(WINDOW *menu_win, int highlight);

//char *choices[] = {
//	"Choice 1",
//	"Choice 2",
//	"Choice 3",
//	"Exit",
//};

vector<string> *choices = new vector<string>();
int n_choices;

void runCurses(char *welcomeString, char *statusString, vector<string> *choices) {
	WINDOW *menu_win;
	int highlight = 1;
	int choice = 0;
	int c;

	initscr();
	clear();
	noecho();
	cbreak();
	int xleave = 6;
	int yleave = 10;
	int WIDTH;
	int HEIGHT;
	getmaxyx(stdscr, HEIGHT, WIDTH);
	HEIGHT = HEIGHT - xleave;
	WIDTH = WIDTH - yleave;
	int startx = (xleave) / 2;
	int starty = (yleave) / 2;

	menu_win = newwin(HEIGHT, WIDTH, starty, startx);
	keypad(menu_win, TRUE);
	mvprintw(0, 0, "Use arrows");
	refresh();
	print_menu(menu_win, highlight);
	while(1) {
		c = wgetch(menu_win);
		switch (c) {
			case KEY_UP:
				if (highlight == 1)
					highlight = n_choices;
				else
					--highlight;
				break;
			case KEY_DOWN:
				if (highlight == n_choices)
					highlight = 1;
				else
					++highlight;
				break;
			case 10:
				choice = highlight;
				break;
			default:
				mvprintw(startx + HEIGHT + 2, 0, "You choose choice %d with choice string %s\n", choice, choices->at(choice - 1).c_str());
				refresh();
				break;
		}
		print_menu(menu_win, highlight);
		if (choice != 0)
			break;
	}
	clrtoeol();
	getch();
	refresh();
	endwin();

	cout << "ENDED" << endl;
}

void print_menu(WINDOW *menu_win, int highlight) {
	int x, y, i;

	x = 2;
	y = 2;

	box(menu_win, 0, 0);

	for (i = 0; i < n_choices; ++i) {
		if (highlight == i + 1) {
			wattron(menu_win, A_REVERSE);
			mvwprintw(menu_win, y, x, "%s", choices->at(i).c_str());
			wattroff(menu_win, A_REVERSE);
		} else {
			mvwprintw(menu_win, y, x, "%s", choices->at(i).c_str());
		}
		++y;
	}
	wrefresh(menu_win);
}

int main(int argc, char **argv) {
	choices->push_back("Choice 1");
	choices->push_back("Choice 2");
	choices->push_back("Choice 3");
	choices->push_back("Exit");

	n_choices = choices->size();
	if (argc > 1) {
		cout << "going to be implemented" << endl;
	} else {
		runCurses();
	}

	return 0;
}

<commit_msg>boilerplate version of ncurses selector<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <ncurses.h>

using namespace std;

void print_menu(WINDOW *menu_win, int highlight, vector<string> *choices);

int runCurses(const char *welcomeString, const char *statusString, vector<string> *choices) {
	WINDOW *menu_win;
	int highlight = 1;
	int choice = 0;
	int c;
	bool done = false;

	initscr();
	clear();
	noecho();
	cbreak();
	int xleave = 6;
	int yleave = 10;
	int WIDTH;
	int HEIGHT;
	getmaxyx(stdscr, HEIGHT, WIDTH);
	HEIGHT = HEIGHT - xleave;
	WIDTH = WIDTH - yleave;
	int startx = (xleave) / 2;
	int starty = (yleave) / 2;

	menu_win = newwin(HEIGHT, WIDTH, starty, startx);
	keypad(menu_win, TRUE);
	mvprintw(0, 0, welcomeString);
	refresh();
	print_menu(menu_win, highlight, choices);
	while(1) {
		c = wgetch(menu_win);
		switch (c) {
			case KEY_UP:
				if (highlight == 1)
					highlight = choices->size();
				else
					--highlight;
				mvprintw(starty + HEIGHT, 0, statusString, highlight, choices->at(highlight - 1).c_str());
				refresh();
				break;
			case KEY_DOWN:
				if (highlight == choices->size())
					highlight = 1;
				else
					++highlight;
				mvprintw(starty + HEIGHT, 0, statusString, highlight, choices->at(highlight - 1).c_str());
				refresh();
				break;
			case 10:
				choice = highlight;
				done = true;
				break;
		}
		print_menu(menu_win, highlight, choices);
		if (done)
			break;
	}
	clrtoeol();
	refresh();
	endwin();
	return choice;
}

void print_menu(WINDOW *menu_win, int highlight, vector<string> *choices) {
	int x, y, i;

	x = 2;
	y = 2;

	box(menu_win, 0, 0);

	for (i = 0; i < choices->size(); ++i) {
		if (highlight == i + 1) {
			wattron(menu_win, A_REVERSE);
			mvwprintw(menu_win, y, x, "%s", choices->at(i).c_str());
			wattroff(menu_win, A_REVERSE);
		} else {
			mvwprintw(menu_win, y, x, "%s", choices->at(i).c_str());
		}
		++y;
	}
	wrefresh(menu_win);
}

int main(int argc, char **argv) {
	vector<string> *choices = new vector<string>();
	choices->push_back("Choice 1");
	choices->push_back("Choice 2");
	choices->push_back("Choice 3");
	choices->push_back("Exit");

	string welcomString = "Use arrays to select";
	string statusString = "You choose choice %d with choice string %s\n";

	const char *ws = welcomString.c_str();
	const char *ss = statusString.c_str();

	if (argc > 1) {
		cout << "going to be implemented" << endl;
	} else {
		int choice = runCurses(ws, ss, choices);
		cout << "selected " << choice << endl;
	}
	return 0;
}

<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2014 Marianne Gagnon

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <vector>
#include "Settings.h"

#include "Utils.h"
#include "DylibBundler.h"

/*
 TODO
 - what happens if a library is not remembered by full path but only name? (support improved, still not perfect)
 - could get mixed up if symlink and original are not in the same location (won't happen for UNIX prefixes like /usr/, but in random directories?)

 FIXME: why does it copy plugins i try to fix to the libs directory?

 */

const std::string VERSION = "1.0.2";

// FIXME - no memory management is done at all (anyway the program closes immediately so who cares?)

std::string installPath = "";

void showHelp()
{
    std::cout << "dylibbundler " << VERSION << std::endl;
    std::cout << "dylibbundler is a utility that helps bundle dynamic libraries inside mac OS X app bundles.\n" << std::endl;

    std::cout << "-x, --fix-file <file to fix (executable or app plug-in)>" << std::endl;
    std::cout << "-b, --bundle-deps" << std::endl;
    std::cout << "-d, --dest-dir <directory to send bundled libraries (relative to cwd)>" << std::endl;
    std::cout << "-p, --install-path <'inner' path of bundled libraries (usually relative to executable, by default '@executable_path/../libs/')>" << std::endl;
    std::cout << "-s, --search-path <directory to add to list of locations searched>" << std::endl;
    std::cout << "-of, --overwrite-files (allow overwriting files in output directory)" << std::endl;
    std::cout << "-od, --overwrite-dir (totally overwrite output directory if it already exists. implies --create-dir)" << std::endl;
    std::cout << "-cd, --create-dir (creates output directory if necessary)" << std::endl;
    std::cout << "-i, --ignore <location to ignore> (will ignore libraries in this directory)" << std::endl;
    std::cout << "-h, --help" << std::endl;
}

int main (int argc, char * const argv[])
{

    // parse arguments
    for(int i=0; i<argc; i++)
    {
        if(strcmp(argv[i],"-x")==0 or strcmp(argv[i],"--fix-file")==0)
        {
            i++;
            Settings::addFileToFix(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-b")==0 or strcmp(argv[i],"--bundle-deps")==0)
        {
            Settings::bundleLibs(true);
            continue;
        }
        else if(strcmp(argv[i],"-p")==0 or strcmp(argv[i],"--install-path")==0)
        {
            i++;
            Settings::inside_lib_path(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-i")==0 or strcmp(argv[i],"--ignore")==0)
        {
            i++;
            Settings::ignore_prefix(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-d")==0 or strcmp(argv[i],"--dest-dir")==0)
        {
            i++;
            Settings::destFolder(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-of")==0 or strcmp(argv[i],"--overwrite-files")==0)
        {
            Settings::canOverwriteFiles(true);
            continue;
        }
        else if(strcmp(argv[i],"-od")==0 or strcmp(argv[i],"--overwrite-dir")==0)
        {
            Settings::canOverwriteDir(true);
            Settings::canCreateDir(true);
            continue;
        }
        else if(strcmp(argv[i],"-cd")==0 or strcmp(argv[i],"--create-dir")==0)
        {
            Settings::canCreateDir(true);
            continue;
        }
        else if(strcmp(argv[i],"-h")==0 or strcmp(argv[i],"--help")==0)
        {
            showHelp();
            exit(0);
        }
        if(strcmp(argv[i],"-s")==0 or strcmp(argv[i],"--search-path")==0)
        {
            i++;
            Settings::addSearchPath(argv[i]);
            continue;
        }
        else if(i>0)
        {
            // if we meet an unknown flag, abort
            // ignore first one cause it's usually the path to the executable
            std::cerr << "Unknown flag " << argv[i] << std::endl << std::endl;
            showHelp();
            exit(1);
        }
    }

    if(not Settings::bundleLibs() and Settings::fileToFixAmount()<1)
    {
        showHelp();
        exit(0);
    }

    std::cout << "* Collecting dependencies"; fflush(stdout);

    const int amount = Settings::fileToFixAmount();
    for(int n=0; n<amount; n++)
        collectDependencies(Settings::fileToFix(n));

    collectSubDependencies();
    doneWithDeps_go();

    return 0;
}
<commit_msg>Update name of macOS in main.cpp<commit_after>/*
The MIT License (MIT)

Copyright (c) 2014 Marianne Gagnon

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */

#include <cstdlib>
#include <cstring>
#include <iostream>
#include <cstdio>
#include <vector>
#include "Settings.h"

#include "Utils.h"
#include "DylibBundler.h"

/*
 TODO
 - what happens if a library is not remembered by full path but only name? (support improved, still not perfect)
 - could get mixed up if symlink and original are not in the same location (won't happen for UNIX prefixes like /usr/, but in random directories?)

 FIXME: why does it copy plugins i try to fix to the libs directory?

 */

const std::string VERSION = "1.0.2";

// FIXME - no memory management is done at all (anyway the program closes immediately so who cares?)

std::string installPath = "";

void showHelp()
{
    std::cout << "dylibbundler " << VERSION << std::endl;
    std::cout << "dylibbundler is a utility that helps bundle dynamic libraries inside macOS app bundles.\n" << std::endl;

    std::cout << "-x, --fix-file <file to fix (executable or app plug-in)>" << std::endl;
    std::cout << "-b, --bundle-deps" << std::endl;
    std::cout << "-d, --dest-dir <directory to send bundled libraries (relative to cwd)>" << std::endl;
    std::cout << "-p, --install-path <'inner' path of bundled libraries (usually relative to executable, by default '@executable_path/../libs/')>" << std::endl;
    std::cout << "-s, --search-path <directory to add to list of locations searched>" << std::endl;
    std::cout << "-of, --overwrite-files (allow overwriting files in output directory)" << std::endl;
    std::cout << "-od, --overwrite-dir (totally overwrite output directory if it already exists. implies --create-dir)" << std::endl;
    std::cout << "-cd, --create-dir (creates output directory if necessary)" << std::endl;
    std::cout << "-i, --ignore <location to ignore> (will ignore libraries in this directory)" << std::endl;
    std::cout << "-h, --help" << std::endl;
}

int main (int argc, char * const argv[])
{

    // parse arguments
    for(int i=0; i<argc; i++)
    {
        if(strcmp(argv[i],"-x")==0 or strcmp(argv[i],"--fix-file")==0)
        {
            i++;
            Settings::addFileToFix(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-b")==0 or strcmp(argv[i],"--bundle-deps")==0)
        {
            Settings::bundleLibs(true);
            continue;
        }
        else if(strcmp(argv[i],"-p")==0 or strcmp(argv[i],"--install-path")==0)
        {
            i++;
            Settings::inside_lib_path(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-i")==0 or strcmp(argv[i],"--ignore")==0)
        {
            i++;
            Settings::ignore_prefix(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-d")==0 or strcmp(argv[i],"--dest-dir")==0)
        {
            i++;
            Settings::destFolder(argv[i]);
            continue;
        }
        else if(strcmp(argv[i],"-of")==0 or strcmp(argv[i],"--overwrite-files")==0)
        {
            Settings::canOverwriteFiles(true);
            continue;
        }
        else if(strcmp(argv[i],"-od")==0 or strcmp(argv[i],"--overwrite-dir")==0)
        {
            Settings::canOverwriteDir(true);
            Settings::canCreateDir(true);
            continue;
        }
        else if(strcmp(argv[i],"-cd")==0 or strcmp(argv[i],"--create-dir")==0)
        {
            Settings::canCreateDir(true);
            continue;
        }
        else if(strcmp(argv[i],"-h")==0 or strcmp(argv[i],"--help")==0)
        {
            showHelp();
            exit(0);
        }
        if(strcmp(argv[i],"-s")==0 or strcmp(argv[i],"--search-path")==0)
        {
            i++;
            Settings::addSearchPath(argv[i]);
            continue;
        }
        else if(i>0)
        {
            // if we meet an unknown flag, abort
            // ignore first one cause it's usually the path to the executable
            std::cerr << "Unknown flag " << argv[i] << std::endl << std::endl;
            showHelp();
            exit(1);
        }
    }

    if(not Settings::bundleLibs() and Settings::fileToFixAmount()<1)
    {
        showHelp();
        exit(0);
    }

    std::cout << "* Collecting dependencies"; fflush(stdout);

    const int amount = Settings::fileToFixAmount();
    for(int n=0; n<amount; n++)
        collectDependencies(Settings::fileToFix(n));

    collectSubDependencies();
    doneWithDeps_go();

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <vector>
#include "GP.hpp"
#include <string>
#include <cstring>
#include <cstdlib>
#include <sstream>

int main() {

    int i, j, n, n_var, v_size;
    double number;

    std::vector<double> x;
    double y;
    std::vector<utils::DataPoint> points;

    std::string next;
    std::string value;

    /********************** RÓTULOS **********************/
    std::string labels;
    bool label;
    char lab;
    std::cout << "O arquivo contem rotulos?\n(S ou N)\n";
    std::cin >> lab;
    if ((lab == 'S')||(lab == 's')) label = true;
    else label = false;     // Caso a resposta seja outra
    /*****************************************************/

    std::cout << "\nFuncao de quantas variaveis?\n";
    std::cin >> n_var;

    std::ifstream DATA ("data.csv");
    if (!(DATA.is_open())) {
        std::cout << "ERROR: File Open\nPlease, close the file and try again.\n" << std::endl;
    }

    while (DATA.good()) {

        if (label) {                        //////////////////////////////
            getline(DATA, labels, '\n');    // Eliminar linha de labels //
            label = false;                  //        (caso haja)       //
        }                                   //////////////////////////////

        getline(DATA, value, ' ');
        std::stringstream(value) >> y;

        value = "";

        for (i=0; i<n_var-1; i++) {
            getline(DATA, value, ' ');
            std::stringstream(value) >> number;
            x.push_back(number);
            value = "";
        }

        getline(DATA, next, '\n');
        std::stringstream(next) >> number;
        x.push_back(number);

        next = "";

        utils::DataPoint point (x,y);

        points.push_back(point);

        x.resize(0);

        std::cout << "\n";

    }

    DATA.close();

    /******************** TESTES ********************/

    std::cout << "Y\t";
    for (j=1; j<=points[0].x.size(); j++) {

        std::cout << "x" << j << "\t";

    }
    std::cout << "\n";

    for (i=0; i<points.size()-1; i++) {

        std::cout << points[i].y << "\t";
        for (j=0; j<(points[i].x).size(); j++) {
            std::cout << points[i].x[j] << "\t";
        }
        std::cout << "\n";
    }

    /***********************************************/
    GP population(100, 2, n_var);

    population.print_GP_d();
    population.calculate_fitness(points);
    population.print_GP_fitness_d();

    return 0;

}
<commit_msg>1.4.1 Ajuste includes<commit_after>#include <iostream>
#include <fstream>
#include <vector>
#include "./headers/GP.hpp"
#include <string>
#include <cstring>
#include <cstdlib>
#include <sstream>

int main() {

    int i, j, n, n_var, v_size;
    double number;

    std::vector<double> x;
    double y;
    std::vector<utils::DataPoint> points;

    std::string next;
    std::string value;

    /********************** RÓTULOS **********************/
    std::string labels;
    bool label;
    char lab;
    std::cout << "O arquivo contem rotulos?\n(S ou N)\n";
    std::cin >> lab;
    if ((lab == 'S')||(lab == 's')) label = true;
    else label = false;     // Caso a resposta seja outra
    /*****************************************************/

    std::cout << "\nFuncao de quantas variaveis?\n";
    std::cin >> n_var;

    std::ifstream DATA ("data.csv");
    if (!(DATA.is_open())) {
        std::cout << "ERROR: File Open\nPlease, close the file and try again.\n" << std::endl;
    }

    while (DATA.good()) {

        if (label) {                        //////////////////////////////
            getline(DATA, labels, '\n');    // Eliminar linha de labels //
            label = false;                  //        (caso haja)       //
        }                                   //////////////////////////////

        getline(DATA, value, ' ');
        std::stringstream(value) >> y;

        value = "";

        for (i=0; i<n_var-1; i++) {
            getline(DATA, value, ' ');
            std::stringstream(value) >> number;
            x.push_back(number);
            value = "";
        }

        getline(DATA, next, '\n');
        std::stringstream(next) >> number;
        x.push_back(number);

        next = "";

        utils::DataPoint point (x,y);

        points.push_back(point);

        x.resize(0);

        std::cout << "\n";

    }

    DATA.close();

    /******************** TESTES ********************/

    std::cout << "Y\t";
    for (j=1; j<=points[0].x.size(); j++) {

        std::cout << "x" << j << "\t";

    }
    std::cout << "\n";

    for (i=0; i<points.size()-1; i++) {

        std::cout << points[i].y << "\t";
        for (j=0; j<(points[i].x).size(); j++) {
            std::cout << points[i].x[j] << "\t";
        }
        std::cout << "\n";
    }

    /***********************************************/
    GP population(100, 2, n_var);

    population.print_GP_d();
    population.calculate_fitness(points);
    population.print_GP_fitness_d();

    return 0;

}
<|endoftext|>


<commit_before>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"

int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t,time; // t for global, time for local
	init_time(t);
	Feat F;

	// Read parameters file
	F.readInputFile(argv[1]);
	printFile(argv[1]);

	// Read galaxies
	Gals G;
	G = read_galaxies(F); // ! Reads all galaxies iff arg2=1
	F.Ngal = G.size();
	printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());

	// Read fiber center positions and compute related things
	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1; // spectrometer has to be identified from 0 to F.Npetal-1
	F.Nfbp = (int) (F.Nfiber/F.Npetal);
	pp.get_neighbors(F); pp.compute_fibsofsp(F);

	// Read plates
	Plates P = read_plate_centers(F);
	F.Nplate = P.size();
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

	// Computes geometry of cb and fh
	F.cb = create_cb();  // cb=central body
	F.fh = create_fh();  // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01; //
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct galaxy> T(G,MinTreeSize);
	print_time(time,"# ... took :");
	//T.stats();

	// For plates/fibers, collect available galaxies
	collect_galaxies_for_all(G,T,P,pp,F);

	// For each galaxy, computes available tilefibers
	collect_available_tilefibers(G,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
	Assignment A(G,F);
	print_time(t,"# Start assignment at : ");

	// Make a plan ----------------------------------------------------
	int interv = 5; //for histograms
	new_assign_fibers(G,P,pp,F,A);   //plans whole survey
	//smooth out distribution of free fibers
	for (int i=0; i<3; i++) {
		print_hist("Unused fibers",interv,histogram(A.unused_fbp(pp,F),interv),false);
		redistribute_tf(G,P,pp,F,A);
	}
    //still not updated, so all QSO targets have multiple observations etc
	for (int i=0; i<2; i++) {
		improve(G,P,pp,F,A);
		print_hist("Unused fibers",interv,histogram(A.unused_fbp(pp,F),interv),false);
		redistribute_tf(G,P,pp,F,A);
		print_hist("Unused fibers",interv,histogram(A.unused_fbp(pp,F),interv),false);
	}

	redistribute_tf(G,P,pp,F,A);
	print_hist("Unused fibers",interv,histogram(A.unused_fbp(pp,F),interv),false);

	// Apply and update the plan --------------------------------------
	init_time_at(time,"# Begin real time assignment",t);
	for (int jj=0; jj<F.Nplate; jj++) {
		int j = A.next_plate;
		printf(" - Plate %d :",j);
		assign_sf_ss(j,G,P,pp,F,A);
		assign_left(j,G,P,pp,F,A); //if unused fibers, assign them
		if (j%500==0) pyplotTile(j,"doc/figs",G,P,pp,F,A);//beautiful picture of positioners, galaxies
		// <-- here is the real observation time
		printf(" %s not as - ",format(5,f(A.unused_f(F,j))).c_str()); fl();
		if (0<=j-F.Analysis) update_plan_from_one_obs(G,P,pp,F,A,F.Nplate-1); else printf("\n");//update once we are far enough along
		//update corrects all future occurrences of wrong QSOs etc and tries to observe something else
		A.next_plate++;

		if (j==200 || j==700 || j==1500 || j==3000 || j==5000 || j==7000) {  //redistribute and improve on various occasions
			redistribute_tf(G,P,pp,F,A);
			improve(G,P,pp,F,A);
		}
	}
	print_time(time,"# ... took :");

	// Results -------------------------------------------------------
	//for (int j=0; j<F.Nplate; j++) write_FAtile(j,F.outDir,G,P,pp,F,A); // Write output
	//overlappingTiles("overlaps.txt",F,A); // Write some overlapping tiles (for S.Bailey)
	print_hist("Unused fibers",interv,histogram(A.unused_fbp(pp,F),interv),false);
	init_time_at(time,"# Display results",t);
	display_results("doc/figs/",G,P,pp,F,A,true);
	print_time(time,"# ... took :");
	//if (F.Verif) A.verif(P,G,pp,F); // Verification that the assignment is sane
	print_time(t,"# Finished !... in");
	return(0);
}
<commit_msg>fix unused_f in main.cpp<commit_after>#include	<cstdlib>
#include	<cmath>
#include	<fstream>
#include	<sstream>
#include	<iostream>
#include	<iomanip>
#include	<string>
#include	<vector>
#include	<algorithm>
#include	<exception>
#include	<sys/time.h>
#include	"modules/htmTree.h"
#include	"modules/kdTree.h"
#include        "misc.h"
#include        "feat.h"
#include        "structs.h"
#include        "collision.h"
#include        "global.h"

int main(int argc, char **argv) {
	//// Initializations ---------------------------------------------
	srand48(1234); // Make sure we have reproducability
	check_args(argc);
	Time t,time; // t for global, time for local
	init_time(t);
	Feat F;

	// Read parameters file
	F.readInputFile(argv[1]);
	printFile(argv[1]);

	// Read galaxies
	Gals G;
	G = read_galaxies(F); // ! Reads all galaxies iff arg2=1
	F.Ngal = G.size();
	printf("# Read %s galaxies from %s \n",f(F.Ngal).c_str(),F.galFile.c_str());

	// Read fiber center positions and compute related things
	PP pp;
	pp.read_fiber_positions(F);
	F.Nfiber = pp.fp.size()/2;
	F.Npetal = max(pp.spectrom)+1; // spectrometer has to be identified from 0 to F.Npetal-1
	F.Nfbp = (int) (F.Nfiber/F.Npetal);
	pp.get_neighbors(F); pp.compute_fibsofsp(F);

	// Read plates
	Plates P = read_plate_centers(F);
	F.Nplate = P.size();
	printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str());

	// Computes geometry of cb and fh
	F.cb = create_cb();  // cb=central body
	F.fh = create_fh();  // fh=fiber holder

	//// Collect available galaxies <-> tilefibers --------------------
	// HTM Tree of galaxies
	const double MinTreeSize = 0.01; //
	init_time_at(time,"# Start building HTM tree",t);
	htmTree<struct galaxy> T(G,MinTreeSize);
	print_time(time,"# ... took :");
	//T.stats();

	// For plates/fibers, collect available galaxies
	collect_galaxies_for_all(G,T,P,pp,F);

	// For each galaxy, computes available tilefibers
	collect_available_tilefibers(G,P,F);

	//results_on_inputs("doc/figs/",G,P,F,true);

	//// Assignment |||||||||||||||||||||||||||||||||||||||||||||||||||
	Assignment A(G,F);
	print_time(t,"# Start assignment at : ");

	// Make a plan ----------------------------------------------------
	int interv = 5; //for histograms
	new_assign_fibers(G,P,pp,F,A);   //plans whole survey
	//smooth out distribution of free fibers
	for (int i=0; i<3; i++) {
		print_hist("Unused fibers",interv,histogram(A.unused_fbp(pp,F),interv),false);
		redistribute_tf(G,P,pp,F,A);
	}
    //still not updated, so all QSO targets have multiple observations etc
	for (int i=0; i<2; i++) {
		improve(G,P,pp,F,A);
		print_hist("Unused fibers",interv,histogram(A.unused_fbp(pp,F),interv),false);
		redistribute_tf(G,P,pp,F,A);
		print_hist("Unused fibers",interv,histogram(A.unused_fbp(pp,F),interv),false);
	}

	redistribute_tf(G,P,pp,F,A);
	print_hist("Unused fibers",interv,histogram(A.unused_fbp(pp,F),interv),false);

	// Apply and update the plan --------------------------------------
	init_time_at(time,"# Begin real time assignment",t);
	for (int jj=0; jj<F.Nplate; jj++) {
		int j = A.next_plate;
		printf(" - Plate %d :",j);
		assign_sf_ss(j,G,P,pp,F,A);
		assign_left(j,G,P,pp,F,A); //if unused fibers, assign them
		if (j%500==0) pyplotTile(j,"doc/figs",G,P,pp,F,A);//beautiful picture of positioners, galaxies
		// <-- here is the real observation time
		printf(" %s not as - ",format(5,f(A.unused_f(j,F))).c_str()); fl();
		if (0<=j-F.Analysis) update_plan_from_one_obs(G,P,pp,F,A,F.Nplate-1); else printf("\n");//update once we are far enough along
		//update corrects all future occurrences of wrong QSOs etc and tries to observe something else
		A.next_plate++;

		if (j==200 || j==700 || j==1500 || j==3000 || j==5000 || j==7000) {  //redistribute and improve on various occasions
			redistribute_tf(G,P,pp,F,A);
			improve(G,P,pp,F,A);
		}
	}
	print_time(time,"# ... took :");

	// Results -------------------------------------------------------
	//for (int j=0; j<F.Nplate; j++) write_FAtile(j,F.outDir,G,P,pp,F,A); // Write output
	//overlappingTiles("overlaps.txt",F,A); // Write some overlapping tiles (for S.Bailey)
	print_hist("Unused fibers",interv,histogram(A.unused_fbp(pp,F),interv),false);
	init_time_at(time,"# Display results",t);
	display_results("doc/figs/",G,P,pp,F,A,true);
	print_time(time,"# ... took :");
	//if (F.Verif) A.verif(P,G,pp,F); // Verification that the assignment is sane
	print_time(t,"# Finished !... in");
	return(0);
}
<|endoftext|>


<commit_before>// OpenLieroX

// Main entry point
// Created 28/6/02
// Jason Boettcher

#include "defs.h"
#include "LieroX.h"
#include "Menu.h"
#include "console.h"

#ifndef WIN32
#include <sys/dir.h>
#include <sys/stat.h>
#endif

// TODO: i hate globals ...
// we have to create a basic class CGame or something

CClient		*cClient = NULL;
CServer		*cServer = NULL;
lierox_t	*tLX = NULL;
game_t		tGameInfo;
CInput		cTakeScreenshot;
CInput		cSwitchMode;

int         nDisableSound = false;

keyboard_t	*kb;
SDL_Surface	*Screen;

CVec		vGravity = CVec(0,4);

char		binary_dir[512];

///////////////////
// Main entry point
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
#ifdef _DEBUG
	_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif // _DEBUG

	InstallExceptionFilter();
	nameThread(-1,"Main game thread");
#endif // _MSC_VER

	printf("OpenLieroX " LX_VERSION " is starting ...\n");

    int     startgame = false;
    float   fMaxFPS = 85;

	strcpy(binary_dir, argv[0]);
	char *slashpos = MAX(strrchr(binary_dir,'/'),strrchr(binary_dir,'\\'));
	if (slashpos)
		*slashpos = 0;
	else
		strcpy(binary_dir, "."); // TODO get exact path of binary

	// Load options and other settings
	if(!LoadOptions())  {
		SystemError("Could not load options");
		return -1;
	}

	if(!LoadNetworkStrings())  {
		SystemError("Could not load network strings.");
		return -1;
	}

    // Parse the arguments
    ParseArguments(argc, argv);

	// Initialize LX
	if(!InitializeLieroX())
		return -1;
	kb = GetKeyboard();
	Screen = SDL_GetVideoSurface();

	// Initialize menu
	if(!Menu_Initialize(&startgame)) {
        SystemError("Error: Could not initialize the menu system.\nError when loading graphics files");
		ShutdownLieroX();
		return -1;
	}

	// TODO: abstract the logging, make an uniform message system
	// Log the game start
	if (tLXOptions->iLogConvos)  {
		FILE *f;

		f = OpenGameFile("Conversations.log","a");
		if (f)  {
			char cTime[26];
			GetTime(cTime);
			fputs("<game starttime=\"",f);
			fputs(cTime,f);
			fputs("\">\r\n",f);
			fclose(f);
		}
	}

	// Setup the global keys
	cTakeScreenshot.Setup(tLXOptions->sGeneralControls[SIN_SCREENSHOTS]);
	cSwitchMode.Setup(tLXOptions->sGeneralControls[SIN_SWITCHMODE]);

	while(!tLX->iQuitGame) {

		startgame = false;

		// Start the menu
		Menu_Start();

		if(startgame) {
			// Start the game
			// this means, start the local server and connect to it
			StartGame();

		} else {
			// Quit
			ShutdownLieroX();
			return 0;
		}

		// Pre-game initialization
		Screen = SDL_GetVideoSurface();
		float oldtime = GetMilliSeconds();
        float captime = GetMilliSeconds();

		ClearEntities();

		ProcessEvents();
		tLX->iQuitEngine = false;
        fMaxFPS = 1.0f / (float)tLXOptions->nMaxFPS;

        //
        // Main game loop
        //
		while(!tLX->iQuitEngine) {

            tLX->fCurTime = GetMilliSeconds();

            // Cap the FPS
            if(tLX->fCurTime - captime < fMaxFPS)
                continue;
            else
                captime = tLX->fCurTime;

            ProcessEvents();

			// Timing
			tLX->fDeltaTime = tLX->fCurTime - oldtime;
			oldtime = tLX->fCurTime;

			// cap the delta
			tLX->fDeltaTime = MIN(tLX->fDeltaTime, 20.0f);

			// Main frame
			GameLoop();

			FlipScreen(Screen);
		}
	}

	ShutdownLieroX();

	return 0;
}

///////////////////
// Parse the arguments
void ParseArguments(int argc, char *argv[])
{
    // Parameters passed to liero xtreme overwrite the loaded options
    char *a;
    for(int i=1; i<argc; i++) {
        a = argv[i];

        // -opengl
        // Turns OpenGL on
        if( stricmp(a, "-opengl") == 0 ) {
            tLXOptions->iOpenGL = true;
        }

        // -noopengl
        // Turns OpenGL off
        if( stricmp(a, "-noopengl") == 0 ) {
            tLXOptions->iOpenGL = false;
        }

        // -nosound
        // Turns off the sound
        if( stricmp(a, "-nosound") == 0 ) {
            nDisableSound = true;
            tLXOptions->iSoundOn = false;
        }

        // -window
        // Turns fullscreen off
        if( stricmp(a, "-window") == 0 ) {
            tLXOptions->iFullscreen = false;
        }

        // -fullscreen
        // Turns fullscreen on
        if( stricmp(a, "-fullscreen") == 0 ) {
            tLXOptions->iFullscreen = true;
        }

        if( !stricmp(a, "-h") || !stricmp(a, "-help") || !stricmp(a, "--help") ) {
        	printf("available parameters:\n");
     		printf("   -opengl\n");
     		printf("   -noopengl\n");
     		printf("   -nosound\n");
     		printf("   -window\n");
     		printf("   -fullscreen\n");
     		exit(0);
        }
    }
}

///////////////////
// Initialize the game
int InitializeLieroX(void)
{
	printf("Hello there, I am initializing me now...\n");

	// Initialize the aux library
	if(!InitializeAuxLib("OpenLieroX","config.cfg",16,0)) {
        SystemError("strange problems with the aux library");
		return false;
	}

	// Initialize the network
    if(!InitNetworkSystem()) {
        SystemError("Error: Failed to initialize the network library");
		return false;
    }

	// Allocate the client & server
	cClient = new CClient;
    if(cClient == NULL) {
        SystemError("Error: InitializeLieroX() Out of memory");
		return false;
    }

	cClient->Clear();

	cServer = new CServer;
    if(cServer == NULL) {
        SystemError("Error: InitializeLieroX() Out of memory on creating CServer");
		return false;
    }

	// Initialize the entities
    if(!InitializeEntities()) {
        SystemError("Error: InitializeEntities() Out of memory on initializing the entities");
		return false;
    }

	// Initialize the LieroX structure
	tLX = new lierox_t;
    if(tLX == NULL) {
        SystemError("Error: InitializeLieroX() Out of memory on creating lierox_t");
		return false;
    }
	tLX->iQuitGame = false;
	tLX->debug_string[0] = 0;
	// TODO: more initiation of the values
	tLX->fCurTime = 0;
	tLX->fDeltaTime = 0;
	// Init this special colour
	tLX->clPink = MakeColour(255,0,255);

	// Load the graphics
    if(!LoadGraphics()) {
        SystemError("Error: Error loading graphics");
		return false;
    }

    // Initialize the console
    if(!Con_Initialize()) {
        SystemError("Error: Could not initialize the console");
        return false;
    }

    // Add some console commands
    Cmd_AddCommand("kick", Cmd_Kick);
	Cmd_AddCommand("ban", Cmd_Ban);
	Cmd_AddCommand("mute", Cmd_Mute);
	Cmd_AddCommand("unmute", Cmd_Unmute);
    Cmd_AddCommand("kickid", Cmd_KickId);
	Cmd_AddCommand("banid", Cmd_BanId);
	Cmd_AddCommand("muteid", Cmd_MuteId);
	Cmd_AddCommand("unmuteid", Cmd_UnmuteId);
	Cmd_AddCommand("crash", Cmd_Crash);
	Cmd_AddCommand("suicide", Cmd_Suicide);
	Cmd_AddCommand("unstuck", Cmd_Unstuck);
	Cmd_AddCommand("wantsjoin", Cmd_WantsJoin);
	Cmd_AddCommand("help", Cmd_Help);
	Cmd_AddCommand("version", Cmd_About);
	Cmd_AddCommand("about", Cmd_About);
	Cmd_AddCommand("fuck", Cmd_BadWord);
	Cmd_AddCommand("ass", Cmd_BadWord);
	Cmd_AddCommand("bitch", Cmd_BadWord);
	Cmd_AddCommand("sex", Cmd_BadWord);
	Cmd_AddCommand("quit", Cmd_Quit);
	Cmd_AddCommand("exit", Cmd_Quit);

	// Load the sounds
	LoadSounds();

	// Load the profiles
	LoadProfiles();

    // Initialize the game info structure
	tGameInfo.iNumPlayers = 0;
    tGameInfo.sMapRandom.psObjects = NULL;

	printf("Initializing ready\n");

	return true;
}

///////////////////
// Start the game
void StartGame(void)
{
    // Clear the screen
    DrawRectFill(SDL_GetVideoSurface(), 0,0, 640,480, 0);

	// Local game
	if(tGameInfo.iGameType == GME_LOCAL) {

		// TODO: uniform message system

		// Start the server
		if(!cServer->StartServer( "local", tLXOptions->iNetworkPort, 8, false )) {
			// ERROR
			//MessageBox(NULL, "Error: Could not start server", "OpenLieroX Error", MB_OK);
			printf("Error: Could not start server\n");
			return;
		}

		// Setup the client
		if(!cClient->Initialize()) {
			// ERROR
			//MessageBox(NULL, "Error: Could not initialize client", "OpenLieroX Error", MB_OK);
			printf("Error: Could not initialize client\n");
			return;
		}

		// Tell the client to connect to the server
		cClient->Connect("127.0.0.1");
	}
}

///////////////////
// Game loop
void GameLoop(void)
{
    if(tLX->iQuitEngine)
        return;

	// Local
	switch (tGameInfo.iGameType)  {
	case GME_LOCAL:
		cClient->Frame();
		cServer->Frame();

		// If we are connected, just start the game straight away (bypass lobby in local)
		if(cClient->getStatus() == NET_CONNECTED) {
			if(cServer->getState() == SVS_LOBBY)
				cServer->StartGame();
		}

		cClient->Draw(Screen);
		break;

	// Hosting
	case GME_HOST:
		//int i;
		cClient->Frame();
		/*if (cBots)
			for (i=0;i<tGameInfo.iNumBots;i++)
				cBots[i].Frame();*/
		cServer->Frame();

		/*if (cBots)
			for (i=0;i<tGameInfo.iNumBots;i++)
				cBots[i].BotSelectWeapons();*/
		cClient->Draw(Screen);
		break;

	// Joined
	case GME_JOIN:
		cClient->Frame();
		cClient->Draw(Screen);
		break;

	} // SWITCH

	// Switch between window and fullscreen mode
	if( cSwitchMode.isDown() )  {
		// Set to fullscreen
		tLXOptions->iFullscreen = !tLXOptions->iFullscreen;

		// Set the new video mode
		SetVideoMode();

		// Update both menu and game screens
		Screen = SDL_GetVideoSurface();
		tMenu->bmpScreen = SDL_GetVideoSurface();
	}

	// We put it here, so the mouse never displays
    SDL_ShowCursor(SDL_DISABLE);

}

///////////////////
// Quit back to the menu
void QuittoMenu(void)
{
	tLX->iQuitEngine = true;
    Menu_SetSkipStart(false);
	cClient->Disconnect();
	/*if (cBots)
		for (int i=0;i<tGameInfo.iNumBots;i++)
			cBots[i].Disconnect();*/
}

///////////////////
// Shutdown the game
void ShutdownLieroX(void)
{
	printf("Shutting me down...\n");

	if (tLXOptions->iLogConvos)  {
		FILE *f;

		f = OpenGameFile("Conversations.log","a");
		if (f)  {
			fputs("</game>\r\n",f);
			fclose(f);
		}
	}

    Con_Shutdown();

	ShutdownGraphics();

	Menu_Shutdown();
	ShutdownProfiles();

    // Free the game info structure
    if(tGameInfo.sMapRandom.psObjects)
        delete[] tGameInfo.sMapRandom.psObjects;

    tGameInfo.sMapRandom.psObjects = NULL;

	// Free the client & server
	if(cClient) {
		cClient->Shutdown();
		delete cClient;
		cClient = NULL;
	}

	if(cServer) {
		cServer->Shutdown();
		delete cServer;
		cServer = NULL;
	}

	// Free the bots
	/*if (cBots)  {
		for (int i=0;i<tGameInfo.iNumBots;i++)
			cBots[i].Shutdown();
		delete[] cBots;
		cBots = NULL;
	}*/

	ShutdownEntities();

	if(tLX) {
		delete tLX;
		tLX = NULL;
	}

	Cmd_Free();

	QuitNetworkSystem();

	ShutdownAuxLib();

	ShutdownOptions();

	printf("Everything was shut down\n");
	printf("Good Bye and enjoy your day...\n");

}
<commit_msg>maxfps fix<commit_after>// OpenLieroX

// Main entry point
// Created 28/6/02
// Jason Boettcher

#include "defs.h"
#include "LieroX.h"
#include "Menu.h"
#include "console.h"

#ifndef WIN32
#include <sys/dir.h>
#include <sys/stat.h>
#endif

// TODO: i hate globals ...
// we have to create a basic class CGame or something

CClient		*cClient = NULL;
CServer		*cServer = NULL;
lierox_t	*tLX = NULL;
game_t		tGameInfo;
CInput		cTakeScreenshot;
CInput		cSwitchMode;

int         nDisableSound = false;

keyboard_t	*kb;
SDL_Surface	*Screen;

CVec		vGravity = CVec(0,4);

char		binary_dir[512];

///////////////////
// Main entry point
int main(int argc, char *argv[])
{
#ifdef _MSC_VER
#ifdef _DEBUG
	_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
#endif // _DEBUG

	InstallExceptionFilter();
	nameThread(-1,"Main game thread");
#endif // _MSC_VER

	printf("OpenLieroX " LX_VERSION " is starting ...\n");

    int     startgame = false;

	strcpy(binary_dir, argv[0]);
	char *slashpos = MAX(strrchr(binary_dir,'/'),strrchr(binary_dir,'\\'));
	if (slashpos)
		*slashpos = 0;
	else
		strcpy(binary_dir, "."); // TODO get exact path of binary

	// Load options and other settings
	if(!LoadOptions())  {
		SystemError("Could not load options");
		return -1;
	}

	if(!LoadNetworkStrings())  {
		SystemError("Could not load network strings.");
		return -1;
	}

    // Parse the arguments
    ParseArguments(argc, argv);

	// Initialize LX
	if(!InitializeLieroX())
		return -1;
	kb = GetKeyboard();
	Screen = SDL_GetVideoSurface();

	// Initialize menu
	if(!Menu_Initialize(&startgame)) {
        SystemError("Error: Could not initialize the menu system.\nError when loading graphics files");
		ShutdownLieroX();
		return -1;
	}

	// TODO: abstract the logging, make an uniform message system
	// Log the game start
	if (tLXOptions->iLogConvos)  {
		FILE *f;

		f = OpenGameFile("Conversations.log","a");
		if (f)  {
			char cTime[26];
			GetTime(cTime);
			fputs("<game starttime=\"",f);
			fputs(cTime,f);
			fputs("\">\r\n",f);
			fclose(f);
		}
	}

	// Setup the global keys
	cTakeScreenshot.Setup(tLXOptions->sGeneralControls[SIN_SCREENSHOTS]);
	cSwitchMode.Setup(tLXOptions->sGeneralControls[SIN_SWITCHMODE]);

	while(!tLX->iQuitGame) {

		startgame = false;

		// Start the menu
		Menu_Start();

		if(startgame) {
			// Start the game
			// this means, start the local server and connect to it
			StartGame();

		} else {
			// Quit
			ShutdownLieroX();
			return 0;
		}

		// Pre-game initialization
		Screen = SDL_GetVideoSurface();
		float oldtime = GetMilliSeconds();

		ClearEntities();

		ProcessEvents();
		tLX->iQuitEngine = false;
		printf("MaxFPS is %i\n", tLXOptions->nMaxFPS);
		float fMaxFrameTime = 1.0f / (float)tLXOptions->nMaxFPS;

        //
        // Main game loop
        //
		while(!tLX->iQuitEngine) {

            tLX->fCurTime = GetMilliSeconds();

            // Cap the FPS
            if(tLX->fCurTime - oldtime < fMaxFrameTime) {
				SDL_Delay((int)((fMaxFrameTime - tLX->fCurTime + oldtime)*1000));
                continue;
			}

            ProcessEvents();

			// Timing
			tLX->fDeltaTime = tLX->fCurTime - oldtime;
			oldtime = tLX->fCurTime;

			// cap the delta
			tLX->fDeltaTime = MIN(tLX->fDeltaTime, 0.5f);

			// Main frame
			GameLoop();

			FlipScreen(Screen);
		}
	}

	ShutdownLieroX();

	return 0;
}

///////////////////
// Parse the arguments
void ParseArguments(int argc, char *argv[])
{
    // Parameters passed to liero xtreme overwrite the loaded options
    char *a;
    for(int i=1; i<argc; i++) {
        a = argv[i];

        // -opengl
        // Turns OpenGL on
        if( stricmp(a, "-opengl") == 0 ) {
            tLXOptions->iOpenGL = true;
        }

        // -noopengl
        // Turns OpenGL off
        if( stricmp(a, "-noopengl") == 0 ) {
            tLXOptions->iOpenGL = false;
        }

        // -nosound
        // Turns off the sound
        if( stricmp(a, "-nosound") == 0 ) {
            nDisableSound = true;
            tLXOptions->iSoundOn = false;
        }

        // -window
        // Turns fullscreen off
        if( stricmp(a, "-window") == 0 ) {
            tLXOptions->iFullscreen = false;
        }

        // -fullscreen
        // Turns fullscreen on
        if( stricmp(a, "-fullscreen") == 0 ) {
            tLXOptions->iFullscreen = true;
        }

        if( !stricmp(a, "-h") || !stricmp(a, "-help") || !stricmp(a, "--help") ) {
        	printf("available parameters:\n");
     		printf("   -opengl\n");
     		printf("   -noopengl\n");
     		printf("   -nosound\n");
     		printf("   -window\n");
     		printf("   -fullscreen\n");
     		exit(0);
        }
    }
}

///////////////////
// Initialize the game
int InitializeLieroX(void)
{
	printf("Hello there, I am initializing me now...\n");

	// Initialize the aux library
	if(!InitializeAuxLib("OpenLieroX","config.cfg",16,0)) {
        SystemError("strange problems with the aux library");
		return false;
	}

	// Initialize the network
    if(!InitNetworkSystem()) {
        SystemError("Error: Failed to initialize the network library");
		return false;
    }

	// Allocate the client & server
	cClient = new CClient;
    if(cClient == NULL) {
        SystemError("Error: InitializeLieroX() Out of memory");
		return false;
    }

	cClient->Clear();

	cServer = new CServer;
    if(cServer == NULL) {
        SystemError("Error: InitializeLieroX() Out of memory on creating CServer");
		return false;
    }

	// Initialize the entities
    if(!InitializeEntities()) {
        SystemError("Error: InitializeEntities() Out of memory on initializing the entities");
		return false;
    }

	// Initialize the LieroX structure
	tLX = new lierox_t;
    if(tLX == NULL) {
        SystemError("Error: InitializeLieroX() Out of memory on creating lierox_t");
		return false;
    }
	tLX->iQuitGame = false;
	tLX->debug_string[0] = 0;
	// TODO: more initiation of the values
	tLX->fCurTime = 0;
	tLX->fDeltaTime = 0;
	// Init this special colour
	tLX->clPink = MakeColour(255,0,255);

	// Load the graphics
    if(!LoadGraphics()) {
        SystemError("Error: Error loading graphics");
		return false;
    }

    // Initialize the console
    if(!Con_Initialize()) {
        SystemError("Error: Could not initialize the console");
        return false;
    }

    // Add some console commands
    Cmd_AddCommand("kick", Cmd_Kick);
	Cmd_AddCommand("ban", Cmd_Ban);
	Cmd_AddCommand("mute", Cmd_Mute);
	Cmd_AddCommand("unmute", Cmd_Unmute);
    Cmd_AddCommand("kickid", Cmd_KickId);
	Cmd_AddCommand("banid", Cmd_BanId);
	Cmd_AddCommand("muteid", Cmd_MuteId);
	Cmd_AddCommand("unmuteid", Cmd_UnmuteId);
	Cmd_AddCommand("crash", Cmd_Crash);
	Cmd_AddCommand("suicide", Cmd_Suicide);
	Cmd_AddCommand("unstuck", Cmd_Unstuck);
	Cmd_AddCommand("wantsjoin", Cmd_WantsJoin);
	Cmd_AddCommand("help", Cmd_Help);
	Cmd_AddCommand("version", Cmd_About);
	Cmd_AddCommand("about", Cmd_About);
	Cmd_AddCommand("fuck", Cmd_BadWord);
	Cmd_AddCommand("ass", Cmd_BadWord);
	Cmd_AddCommand("bitch", Cmd_BadWord);
	Cmd_AddCommand("sex", Cmd_BadWord);
	Cmd_AddCommand("quit", Cmd_Quit);
	Cmd_AddCommand("exit", Cmd_Quit);

	// Load the sounds
	LoadSounds();

	// Load the profiles
	LoadProfiles();

    // Initialize the game info structure
	tGameInfo.iNumPlayers = 0;
    tGameInfo.sMapRandom.psObjects = NULL;

	printf("Initializing ready\n");

	return true;
}

///////////////////
// Start the game
void StartGame(void)
{
    // Clear the screen
    DrawRectFill(SDL_GetVideoSurface(), 0,0, 640,480, 0);

	// Local game
	if(tGameInfo.iGameType == GME_LOCAL) {

		// TODO: uniform message system

		// Start the server
		if(!cServer->StartServer( "local", tLXOptions->iNetworkPort, 8, false )) {
			// ERROR
			//MessageBox(NULL, "Error: Could not start server", "OpenLieroX Error", MB_OK);
			printf("Error: Could not start server\n");
			return;
		}

		// Setup the client
		if(!cClient->Initialize()) {
			// ERROR
			//MessageBox(NULL, "Error: Could not initialize client", "OpenLieroX Error", MB_OK);
			printf("Error: Could not initialize client\n");
			return;
		}

		// Tell the client to connect to the server
		cClient->Connect("127.0.0.1");
	}
}

///////////////////
// Game loop
void GameLoop(void)
{
    if(tLX->iQuitEngine)
        return;

	// Local
	switch (tGameInfo.iGameType)  {
	case GME_LOCAL:
		cClient->Frame();
		cServer->Frame();

		// If we are connected, just start the game straight away (bypass lobby in local)
		if(cClient->getStatus() == NET_CONNECTED) {
			if(cServer->getState() == SVS_LOBBY)
				cServer->StartGame();
		}

		cClient->Draw(Screen);
		break;

	// Hosting
	case GME_HOST:
		//int i;
		cClient->Frame();
		/*if (cBots)
			for (i=0;i<tGameInfo.iNumBots;i++)
				cBots[i].Frame();*/
		cServer->Frame();

		/*if (cBots)
			for (i=0;i<tGameInfo.iNumBots;i++)
				cBots[i].BotSelectWeapons();*/
		cClient->Draw(Screen);
		break;

	// Joined
	case GME_JOIN:
		cClient->Frame();
		cClient->Draw(Screen);
		break;

	} // SWITCH

	// Switch between window and fullscreen mode
	if( cSwitchMode.isDown() )  {
		// Set to fullscreen
		tLXOptions->iFullscreen = !tLXOptions->iFullscreen;

		// Set the new video mode
		SetVideoMode();

		// Update both menu and game screens
		Screen = SDL_GetVideoSurface();
		tMenu->bmpScreen = SDL_GetVideoSurface();
	}

	// We put it here, so the mouse never displays
    SDL_ShowCursor(SDL_DISABLE);

}

///////////////////
// Quit back to the menu
void QuittoMenu(void)
{
	tLX->iQuitEngine = true;
    Menu_SetSkipStart(false);
	cClient->Disconnect();
	/*if (cBots)
		for (int i=0;i<tGameInfo.iNumBots;i++)
			cBots[i].Disconnect();*/
}

///////////////////
// Shutdown the game
void ShutdownLieroX(void)
{
	printf("Shutting me down...\n");

	if (tLXOptions->iLogConvos)  {
		FILE *f;

		f = OpenGameFile("Conversations.log","a");
		if (f)  {
			fputs("</game>\r\n",f);
			fclose(f);
		}
	}

    Con_Shutdown();

	ShutdownGraphics();

	Menu_Shutdown();
	ShutdownProfiles();

    // Free the game info structure
    if(tGameInfo.sMapRandom.psObjects)
        delete[] tGameInfo.sMapRandom.psObjects;

    tGameInfo.sMapRandom.psObjects = NULL;

	// Free the client & server
	if(cClient) {
		cClient->Shutdown();
		delete cClient;
		cClient = NULL;
	}

	if(cServer) {
		cServer->Shutdown();
		delete cServer;
		cServer = NULL;
	}

	// Free the bots
	/*if (cBots)  {
		for (int i=0;i<tGameInfo.iNumBots;i++)
			cBots[i].Shutdown();
		delete[] cBots;
		cBots = NULL;
	}*/

	ShutdownEntities();

	if(tLX) {
		delete tLX;
		tLX = NULL;
	}

	Cmd_Free();

	QuitNetworkSystem();

	ShutdownAuxLib();

	ShutdownOptions();

	printf("Everything was shut down\n");
	printf("Good Bye and enjoy your day...\n");

}
<|endoftext|>


<commit_before>#include "HumbugWindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    HumbugWindow w;
    if (argc == 3 && QString(argv[1]) == QString("--site")) {
        w.setUrl(QUrl(argv[2]));
    }
    w.show();

    return a.exec();
}
<commit_msg>Declare an application name and version.<commit_after>#include "HumbugWindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    a.setApplicationName("Humbug Desktop");
    a.setApplicationVersion("0.1");

    HumbugWindow w;
    if (argc == 3 && QString(argv[1]) == QString("--site")) {
        w.setUrl(QUrl(argv[2]));
    }

    w.show();

    return a.exec();
}
<|endoftext|>