/**
 * \file st_raw.c
 * \brief This file implements the loading the RAW image from the STM camera.
 *
 * The format is really raw. An array of 2 byte values 1024x512. No header
 *
 *  Created on: Jul 6, 2009
 *      Author: Alexander Pimenov
 */

#include "global.h"
#include <stdio.h>
#include <stdlib.h>
#include "g12buffer.h"


#define ST_BYTE_PER_PIXEL 2
#define ST_CAMERA_H    512
#define ST_CAMERA_W    1024


G12Buffer* g12BufferCreateFromSTRaw (char *RawName){
	FILE* fp;
	G12Buffer *toReturn = NULL;
	int i,j;

	//Open file for Reading in Binary Mode
	fp = fopen(RawName, "rb");

	if (fp == NULL) {
		printf("Image %s does not exist \n", RawName);
		goto cleanup;
	}

	fseek(fp, 0, SEEK_END);
	long counter = ftell(fp);
	fseek(fp, 0, SEEK_SET);

	if (counter != ST_CAMERA_H * ST_CAMERA_W * ST_BYTE_PER_PIXEL)
	{
		printf("Image file %s does not contain a valid ST image \n", RawName);
		goto cleanup;
	}
	toReturn = g12BufferCreate(ST_CAMERA_H, ST_CAMERA_W);
	uint8_t *data = (uint8_t *)dv_malloc(ST_CAMERA_H * ST_CAMERA_W * ST_BYTE_PER_PIXEL);
	if (data == NULL)
	{
		printf("Could not allocate memory");
		goto cleanup;
	}
	fread(data, ST_BYTE_PER_PIXEL, ST_CAMERA_H * ST_CAMERA_W, fp);

	for (i = 0; i < ST_CAMERA_H; i++)
		for (j = 0; j < ST_CAMERA_W; j++)
		{
			uint16_t byte1 = data[(i * ST_CAMERA_W + j) * 2];
			uint16_t byte2 = data[(i * ST_CAMERA_W + j) * 2 + 1];

			G12ELEM(toReturn, j,i) = (byte1 >> 4)  | (byte2 << 4);
		}

cleanup:
	if (fp != NULL)
		fclose(fp);
	if (data != NULL)
		dv_free(data);
	return toReturn;
}
