/*************************************************************************************************************
* This file contains all important core functions
* 2012/10 by Dlxko
* Version 4.0
**************************************************************************************************************/
#include "Functions.h"

// Variables
static int index;
static int counter;
static int int_packet_len;
static bool found;

// Function to extract some data from packet or array ( only chars )
void function_midcopy ( char* input, char* output, int start_pos, int stop_pos)
{
	// Counter
	index = 0;
	counter = start_pos;

	// Cycle
	do
	{
		// Transfer
		output[index] = input[counter];
		index++;
		counter++;
	}
	while ( counter < stop_pos);

	// Output value
	output[index] = 0;
}

// Function to convert package lenght from char to int
int function_convert_packet_lenght(char function_char_lenght[LENGHT_SIZE+1])
{
	// Alloc + reset
	int_packet_len = 0;
	char *char_packet_len;

	// Convert and get informations
	if (strlen(function_char_lenght) > 0)
	{
		char_packet_len = function_char_lenght;
		int_packet_len = atoi( char_packet_len );
	}
	else int_packet_len = 0;
	return int_packet_len;
}

// Function to get buddy name from number
int function_get_buddy_number(char nick_name[10])
{
	// Use counter and found bool
	counter = 0;
	found = false;

	//Cycle
	do
	{
		// Prevent crash and compare
		if ( buddy[counter].nick_name )
			if ( (strcmp(buddy[counter].nick_name, nick_name)) == 0 )
			{
				found = true;
				break;
			}
			++counter;
	}
	while ( counter < MAX_BUDDIES );

	// Check if found
	if (found == false)
		counter = MAX_BUDDIES + 1;

	// Return buddy number
	return counter;
}

// Function to send datas
void function_send_data (char *buffer, int size )
{
	// Store the return information about the sending
	index = send ( s, buffer, size, 0 );

	// Check for errors
	if ( ( index == SOCKET_ERROR ) || ( index != size )  || ( index == INVALID_SOCKET ) )
	{
		memset(dialog_text, 0, DIALOG_BUFFER_SIZE);
		sprintf_s(dialog_text, DIALOG_BUFFER_SIZE, "%s : %d", LANG_SENDING_PACKET_ERORR, index);
		function_show_warning(dialog_text);
	}
}