'RECOVER code returns 51 jpegs and are incorrect i need some cues

So I'm trying CS50 Recover exercise (where you need to search for jpg files in a memory card and whenever you find one- you open a new file and write the jpg found to the new file). My code compiles and returns 51 jpegs instead of only 50 and all of them are incorrect. Please, I need some cues on what to focus at and fix/replace.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
     // Check for valid usage
    if ( argc != 2)
    {
        printf("Usage: ./recover IMAGE\n");
        return 1;
    }

    // Check for valid image
    FILE *image = fopen(argv[1], "r");

    if (image == NULL)
    {
        return 1;
    }


        BYTE buffer[512];
        int i = 0;
        char new_image[8];
        FILE *output;
        FILE *output1;
        while (fread (buffer, 1, 512, image) == 512)
        {


            // IF Start of a JPEG
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && ((buffer[3] & 0xf0) == 0xe0))
        {
            sprintf(new_image, "%03i.jpg", i);
          //if  first JPEG
                if ( i == 0)
               {
                    output = fopen(new_image, "w");
                 fwrite(buffer, 512, 1, output);
                 i++;
               }
         // if not first JPEG
                else
               {
               fclose(output);
               sprintf(new_image, "%03i.jpg", i);
               output1 = fopen(new_image, "w");
               fwrite(buffer, 1, 512, output1);
               fclose(output1);
               i++;
               }
        }
        // if not start of a JPEG
        else
        {
            output = output1 = fopen(new_image, "w");
            fwrite(buffer, 1, 512, output);

        }

        }
        fclose(image);

}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source