#include "bmp.h"
#include "rotation.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>



int main(int argc, char *argv[]) {
  if (argc != 4) {
    printf("Usage: ./image-transformer <source-image> <transformed-image> <angle>\n");
    return 1;
  }

  char* source_image_filename = argv[1];
  char* transformed_image_filename = argv[2];
  int angle = atoi(argv[3]);

  if (angle % ANGLE_STEP != 0 || angle < MIN_ANGLE || angle > MAX_ANGLE) {
    printf("Invalid angle. Angle must be one of: 0, 90, -90, 180, -180, 270, -270\n");
    return 1;
  }

  FILE* source_file = fopen(source_image_filename, "rb");
  if (!source_file) {
    printf("Error opening source image file\n");
    return 1;
  }
  
  struct image original_img = { 0 };
  int read_result = from_bmp(source_file, &original_img);
  if (read_result != READ_SUCSESS) {
    fclose(source_file);
    printf("Error reading source image\n");
    return 1;
  }

  struct image final_img = { 0 };
  final_img = rotate_image(&original_img, angle);

  FILE* transformed_file = fopen(transformed_image_filename, "wb");
  if (!transformed_file) {
    printf("Error opening transformed image file\n");
    return 1;
  }
  
  int write_result = to_bmp(transformed_file, &final_img);
  if (write_result!=WRITE_SUCSESS){
    fclose(transformed_file);
    printf("Error writing rotated image\n");
    return 1;
  }
  fclose(source_file);
  fclose(transformed_file);
  return 0;
}