using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;

namespace ImageProcessingDemo
{

	public class RandomAccessBitmap : IDisposable
	{
		protected BitmapData bmd = null;
		protected Bitmap bmp = null;

		protected RandomAccessBitmap(Bitmap bitmap, PixelFormat pf)
		{
			bmp = bitmap;
			bmd = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.ReadWrite, pf);
		}

		public void Dispose()
		{
			if (bmp != null)
			{
				bmp.UnlockBits(bmd);
				bmp = null;
			}
			else
				throw new ObjectDisposedException("RandomAccessBitmap");

		}

		public int Width
		{
			get
			{
				if (bmp != null)
					return bmp.Width;
				else
					throw new ObjectDisposedException("RandomAccessBitmap");
			}
		}

		public int Height
		{
			get
			{
				if (bmp != null)
					return bmp.Height;
				else
					throw new ObjectDisposedException("RandomAccessBitmap");
			}
		}
	}

	public class RandomAccessRGBBitmap : RandomAccessBitmap
	{
		public RandomAccessRGBBitmap(Bitmap bmp)
			: base(bmp, PixelFormat.Format24bppRgb)
		{ /* Nothing to do here */ }
		public unsafe Color this[int x, int y]
		{
			get
			{
				byte* p = (byte*)bmd.Scan0 + y * bmd.Stride + x * 3;
				return Color.FromArgb(p[0], p[1], p[2]);
			}
			set
			{
				byte* p = (byte*)bmd.Scan0 + y * bmd.Stride + x * 3;
				p[0] = (byte)value.R;
				p[1] = (byte)value.G;
				p[2] = (byte)value.B;
			}
		}
	}
}