#include <stdio.h>
#include <stdlib.h>

float** allocateWeightsMatrices(int layerNeurons, int weightsPerNeuron) {
	float** weightsMatrix;
	if ((weightsMatrix = (float**)malloc(layerNeurons*sizeof(float*))) == NULL) {
		printf("Error allocating memory");
		exit(1);
	}

	for (int neuron_index = 0; neuron_index < layerNeurons; neuron_index++) 	{
		if ((weightsMatrix[neuron_index] = (float*)malloc(sizeof(float)*weightsPerNeuron)) == NULL)		{
			printf("Error allocating memory");
			exit(1);
		}
	}
	return weightsMatrix;
}

int readLayerWeights(FILE* weightsFile, float** weightsMatrix, int totalNeurons, int weightsPerNeuron) {
	float tmp_float;

	for (int neuron_index = 0; neuron_index < totalNeurons; neuron_index++) {
		for (int weight_index = 0; weight_index < weightsPerNeuron; weight_index++) {
			int res = fread(&tmp_float, sizeof(float), 1, weightsFile);
			if (res == -1)
			{
				printf("Error - reached end of file?\n");
				return 0;
			}
			else
			{
				weightsMatrix[neuron_index][weight_index] = tmp_float;
				printf("Weight read = %f\n", tmp_float);
			}
		}

	}
	return 1;
}

int main()
{
	FILE *weightsFile;
	int netInputs = 784;
	int hiddenLayerNeurons = 1000;
	int outputLayerNeurons = 10;

	// Hidden Layer Weights
	float** hiddenLayerWeights=NULL;
	hiddenLayerWeights = allocateWeightsMatrices(hiddenLayerNeurons, netInputs + 1); //+ 1 for bias
	
	// Output Layer Weights
	float** outputLayerWeights = NULL;
	outputLayerWeights = allocateWeightsMatrices(outputLayerNeurons, hiddenLayerNeurons + 1); //+ 1 for bias
	
	//Open file
	fopen_s(&weightsFile, ".....your-path.....\1000HU_BinaryFloatWeights.txt", "rb");
	if (!weightsFile) 	{
		printf("Unable to open weights file \n");
	}
	else 	{
		// Read all weights
		readLayerWeights(weightsFile, hiddenLayerWeights, hiddenLayerNeurons, netInputs + 1);
		readLayerWeights(weightsFile, outputLayerWeights, outputLayerNeurons, hiddenLayerNeurons + 1);
	}

	//TODO: Free weight matrices memory
	return 0;
}