/*
 *  A function illustrating how to link C code to code generated from LLVM 
 */
#include<stdio.h>
#include<stdlib.h>
#include <unistd.h>
#define RGB_COMPONENT_COLOR 255

double conv_to_float(int* i);
double conv_to_float2(int i);
int write_image(int*,int, int, char*);
int conv_to_int(double* i);
int conv_to_int2(double i);

int write_image(int *c,int nrows,int ncols, char* filename){
	FILE *f = fopen(filename,"wb");
	if (f==NULL){
		printf("Error opening file!\n");
		exit(1);
	}
	fprintf(f,"P3\n");
	fprintf(f,"%d %d\n",ncols,nrows);
	fprintf(f,"255\n");
	
	int i,j,k;
	for(i=0;i<nrows;i++){
		for(j=0;j<ncols*3;j++){
				fprintf(f,"%d", *(c++));
				fprintf(f," ");
		}
		fprintf(f,"\n");
	}
	fclose(f);
	return 0;
}

int* read_image(char *filename)
{
 int ncols;
    int nrows;
    int max_colour;
    int x;
    int i = 0;

    FILE *f = fopen(filename,"rb");
    if (f==NULL){
        printf("Error opening file!\n");
        exit(1);
    }

    fscanf (f, "P3 %d %d %d", &ncols, &nrows, &max_colour);

    int *temp= malloc((ncols*nrows*3+2)*sizeof(int));
    if(temp == NULL)
    {
        printf("malloc returned null");
        exit(1);
    }

    temp[0] = ncols;
    temp[1] = nrows;
    for(i=2;i<ncols*nrows*3+2;i=i+1){
        fscanf(f,"%d",&x);
        temp[i] = x;
    }

    fclose(f);
    return (temp);

}

int conv_to_int(double* i) {
//	printf("before: %f after: %d\n", *i, (int)*i);
	return (int) *i;
}

int conv_to_int2(double i) {
	return (int) i;
}

double conv_to_float(int* i) {
//	printf("before: %d after: %f\n", *i, (double)*i);
	return (double) *i;
}

double conv_to_float2(int i) {
	return (double) i;
}

