#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <zlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main( int argc, char *argv[] )
{
  FILE *input_file;
  char *file_buffer;
  unsigned long file_size;
  unsigned long chunk_size=1024;
  unsigned long bytes_read;
  unsigned long crc=0L;
  unsigned long buffer_index;
  int input_fd;

  printf( "crc32.c by elektron\n");
  if( argc < 2 )
  {
    printf( "I need a filename to calculate crc on\n" );
    return 1;
  }

  printf( "File Name: %s\n", argv[1] );
  input_file = fopen( argv[1], "r" );
  if( input_file == NULL )
  {
    printf( "Could not open %s for reading.\n", argv[1] );
    return 2;
  }

  fseek( input_file, 0, SEEK_END );
  file_size = ftell( input_file );
  rewind( input_file);

  printf( "File Size: %lu\n", file_size );

  if( file_size == 0 )
  {
    printf( "File size is calculated to be 0. Cannot calculate CRC\n" );
    return 3;
  }
  file_buffer = (char *)malloc( chunk_size+1 );
  if( file_buffer == NULL )
  {
    printf( "Unable to reserve enough memory for file buffer.\n" );
    return 4;
  }
  crc = crc32( crc, Z_NULL, 0 );

  input_fd = open( argv[1], O_RDONLY );
  if( input_fd == -1 )
  {
    printf( "Could not open %s for reading.\n", argv[1] );
    return 2;
  }
 while( 1 ){

 bytes_read = read( input_fd, file_buffer, chunk_size );

 if (bytes_read == 0 ) {
        break;
 }
 if (bytes_read == -1 ) {
        perror("read");
        break;
 }

  crc = crc32( crc, (const Bytef *)file_buffer, chunk_size );

}
  printf("Calculated CRC: %lu\n", crc );

  free( file_buffer );

  return 0;
}
