using System;
using System.IO;

namespace BMP_example
{
    class Program
    {
        static void Main(string[] args)
        {
            using (FileStream file = new FileStream("sample.bmp", FileMode.Create, FileAccess.Write))
            {

                // Define BMP header (with correct file size)
                int width = 500, height = 1000;


                int rowSize = (width + 31) / 32 * 4; // Ensure row size is multiple of 4 bytes
                
                int fileSize = 62 + (height * rowSize);




                // A monochrome 1000x1000 pixel BMP image is created
                file.Write(
                    new byte[62]
                    {
                        // Header
                        0x42, 0x4d,     // Signature 'BM'
                        (byte)(fileSize), (byte)(fileSize >> 8), (byte)(fileSize >> 16), (byte)(fileSize >> 24),  // File size
                        0x0, 0x0, 0x0, 0x0,
                        0x3e, 0x0, 0x0, 0x0,
                        // Header information
                        0x28, 0x0, 0x0, 0x0,

                        (byte)(width), (byte)(width >> 8), 0x00, 0x00,  // Image width
                        (byte)(height), (byte)(height >> 8), 0x00, 0x00, // Image height
                        
                        0x01, 0x00,                 // Number of color planes (1)
                        0x01, 0x00,                 // Bits per pixel (1-bit monochrome)
                        0x0, 0x0, 0x0, 0x0,
                        0x0, 0xf4, 0x0, 0x0,
                        0x0, 0x0, 0x0, 0x0,
                        0x0, 0x0, 0x0, 0x0,
                        0x02, 0x00, 0x00, 0x00,     // Number of colors in palette (2 for monochrome)
                        0x0, 0x0, 0x0, 0x0,


                        // Color table (can be changed to black and white)
                        0xff, 0x0, 0x0, 0x0, 
                        0x0, 0x0, 0xff, 0x0
                    }
                 );

                // Calculate the number of bytes in a BMP image row (multiple of 4): 1000 bits / 32 bits = 31.25, 
                // so in this case the row will require 32 bytes of 4
                int l = (width + 31) / 32 * 4;
                Console.WriteLine(l);

                // Define the array for the pixels. The color of the first pixel in the array corresponds to the value of the first bit.
                var t = new byte[height * l]; 
                // Draw a 128x128 pixel square, whose bottom-left corner coincides with the bottom-left corner of the BMP image.



                // Draw a vertical line across the entire image at y = 7.
                int middle =  (width / 2) / 8;

                for (int i = middle; i < height * l; i += l)
                    t[i] ^= 1; // same as t[i] ^= 0b10000001;  -> is the same

                file.Write(t);
                file.Close();
            }
        }
    }
}
