//-----------------------------------------------------------------------------
// structreadwrite.c
//
// programm will write the content of a struct into a binary file
// programm will read from a binary file into a struct
//
// group: group 1,13 study assistant AltiHar
//
// author: Altinger Harald 0630xxx
//
// last change: created all (Altinger Harald)
//-----------------------------------------------------------------------------
//

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//define error codes
#define OUT_OF_MEMORY -1

//define a new dataype
typedef struct
{
	int color;
	int x_pos_start;
	int y_pos_start;
	int x_pos_end;
	int y_pos_end;
} Line;

//forward declaration
void printLine(Line *line);

//-----------------------------------------------------------------------------
///
/// main function to controll the program flow
///
/// @return int  allways 0
//
int main()
{
    FILE *dest_file = fopen( "output.txt", "wb" );
    FILE *src_file = fopen( "output.txt", "rb" );
    
	int elements_written = 0;
	int elements_read = 0;	

	Line *line_to_write = malloc(sizeof(Line));
	if(line_to_write == NULL)
	{
	  return OUT_OF_MEMORY;
	}
	
	Line *line_to_read = malloc(sizeof(Line));
	if(line_to_read == NULL)
	{
	  free(line_to_write);
	  return OUT_OF_MEMORY;
	}
	
	line_to_write->color = 0xffffff;
	line_to_write->x_pos_start = 10;
	line_to_write->x_pos_end = 10;
	line_to_write->y_pos_start = 10;
	line_to_write->y_pos_end = 10;
	
    if( dest_file != NULL )
    {
      elements_written = fwrite(line_to_write,sizeof(Line),1, dest_file);
    }
    printf("elements written to file %d\n",elements_written);
    printLine(line_to_write);
    
    fclose(dest_file);
    free(line_to_write);
    
    if( dest_file != NULL )
    {
      elements_read = fread(line_to_read,sizeof(Line),1, src_file);
    }
    printf("elements read from file %d\n",elements_read);
    printLine(line_to_read);
    
    fclose(src_file);
    free(line_to_read);
    
    return 0;
}

//-----------------------------------------------------------------------------
///
/// main function to controll the program flow
///
/// @return int  nummber of calling arguments
//
void printLine(Line *line)
{
	printf("color %x\n",line->color );
	printf("from(%d,%d) to (%d,%d) \n",line->x_pos_start,
	  line->x_pos_end,line->y_pos_start,line->y_pos_end );	
}


