LESSER THE MARKS MORE IS THE HUNGER TO DO WELL AND YOU EXPLORE NEW WAYS TO DO THINGS BETTER. SO DONT WORRY ABOUT MARKS


Monday, October 10, 2011

ULTRASOUND BIRDS VIEW PART 4

IMAGE ACQUISITION

After transducer sends the short duration pulse and the echo is reflected back ,the transducer converts the echo into an electronic pulse that can be converted into digital format using the ADC ,The X and Y co-ordinates are specified by the position generator that uses the time of travel for the ultrasonic pulse and position sensor for beam direction .The signal amplitude and position co-ordinates for multiple line of sight are placed temporarily in the buffer before final storage in RAM .Changing the shade of Gray level could improve the quality of image and it can be done well processing techniques that could be a TGC ,Edge enhancement ,logarithmic compression ,fill in interpolation ,selective enhancement ,Image updating and write zoom

· Time Gain Compensation:: Ultrasound attenuates as it propagates through the body. When used to image the biological tissues, the echo signals need to be progressively amplified to allow the visualization of the shallow regions simultaneously with the deeper regions. Time Gain Compensation, or TGC, is that amplification step. The amplification coefficient, or gain, needs to increase with depth, as the signal gets smaller and smaller. But in ultrasound imaging, the speed of sound is usually assumed to be constant, creating a direct equivalence between distance and time (TGC) Time gain compensation is the signal processing control that allows the sonographer to amplify the returning signal from deeper structures in the body. The TGC control compensates for the attenuation of sound waves.

· Edge Enhancement :: ultrasound imaging require to detect the interface or boundaries between one structure and another . Edge enhancement is a filtering technique

Pixel no

1

2

3

4

5

6

7

8

Original value

200

200

200

200

100

100

100

100

Kernel

-1

3

-1

Edge enhanced value

200

200

200

300

0

100

100

100

Suppose eight pixels along one line of sight have initial values as in the table, the filtering process uses a Kernel (collection of weighing factors or convolution coefficient) to calculate the edge enhanced value for pixel number 4

New value =200 × -1 + 200 × 3 + 100 × -1 ==300

Similarly move the window for other pixel values

· Logarithmic Compression :: Compression is necessary because the display device is unable to process an extremely wide range of signal level

· Fill in Interpolation:: The scanned area are represented as pixel values in the image matrix and some matrix area are not filled which could have a value “0” and it could like a chess box so the area with “0” matrix is replaced by averaged signals of the nearby matrix

· Selective Enhancement :: In addition to TGC there are keys provided for selective enhancement ,this is because amplification is in a non uniform manner ,by selective enhancement the amplification is done as a function of depth ,each key corresponds to certain depth

· Write Zoom :: also called as regional expansion ,this is required to zoom an area of a region

POST PROCESSING TECHNIQUES

· Black And white inversion :: Pixel value of 240 which is normally depicted as white is depicted as near black on the inverted image

· Freeze Frame :: when freeze frame is used the interested area is used for prolonged viewing and updating of output buffer is discontinued

· Frame averaging or Persistence :: this helps in increasing signal noise ratio ,frame averaging allows successive frames to be added together to increase SNR

· Contrast enhancement :: Contrast enhancement is an powerful technique ,suppose Gray value from 0-56 are of no use as they are weak signals and not of interest they can be eliminated by redistributing these gray scales

· Smoothing :: is an image processing technique used to reduce random noise ,Random noise is a parameter that describes the variation of signal level associated with a particular interface

· Distance calculation ::

ULTRASOUND BIRDS VIEW PART 3

DIGITAL SIGNAL AND IMAGE PROCESSING

Some accuracy is sacrificed when digital scan converter is used, the loss of accuracy occurs in the translation of information from detection system (signal amplitude and location of the reflecting structure) to a form that is understood by the computer, this process could be called as analog to digital conversion and limited by the number of bits available in the digitization process. In ultrasound the analog signal is a voltage wave form generated by the returning echo striking the Transducer , increased intensity relates to increased voltage

Now let us study using a example rather than theory ,for this let us take two ADC for two different types of scanner just for better understanding and these scanner are configured to digitize the signal over a range of 0v to 5v,Scanner A has a 2bit (4 discrete steps)ADC and Scanner B has a 3(8 discrete steps) bit ADC.The corresponding step size is calculated by dividing the range (5V) by the total number of discrete steps available (either 4 for 2bit OR 8 for 3 bit) which would give a value of( 5/4=1.25V) and (5/8=0.625V).Now if the signal peak corresponds to 1.25V then when digitilasied gives a value of (1.25/1.25=1) for a 2 bit scanner would be (01) in case for a 3 bit scanner if the voltage level is 1.875V volts then for a 3 bit scanner it would be (1.875/0.625=3) that would be (011). The accuracy of the scanner can be increased by increasing the bit depth

SPATIAL REPRESENTATION

The information obtained from the scanned area is divided into small, square picture elements called “pixels” which are combined as building blocks to form the image .During data collection the digitalized signal is stored in a particular location of memory specified by the address .Each pixel has one location reserved in memory for holding the amplitude of the signal associated with that pixel. The address is determined from x and y coordinates, generated by transducer positioning –sensing electronics and time between the transmitted pulse and the received echo

This is analogues to a Puzzle where in the piece of puzzle is restricted to a square, each of which has a uniform shade, but only the value is stored in memory for each pixel .The same value is assumed to exist throughout the pixel ,here some accuracy is sacrificed by digital representation of spatial resolution


ULTRASOUND BIRDS VIEW PART 2

ECHO RANGING

In diagnostic ultrasound reflection of sound beam from interface along the ultrasonic path are of primary importance ,An ultrasound wave is transmitted from the body strikes an interface and is partially reflected back to the transducer as determined by the percentage of reflection formula .The reflected ultrasound waves ,arising from the various acoustic impedance mismatch results in ultrasonic detection of interfaces within the body

D=ct

T=time of travel

STATIC IMAGING PRINCIPLES AND INSTRUMENTATION

SONAR plays a major role in development of medical diagnostic ultrasound instrumentation particularly A mode scanning, Transmission mode scanning, the only tech that does not rely on ECHO RANGING principle

A MODE SCANNING PRINCIPLE AND INSTRUMENTATION

This is based on ECHO ranging principle. The term A refers to amplitude which is nothing but the magnitude of the signal as a spike (strength) in one dimension, against the depth of the signal ,depth is directly proportional to time .An increase in the amplitude or strength of the signal give rise to an increase in height of the spike .The variation in strength is the result of percentage of reflectance from the different interfaces and the attenuation of the beam as the ultrasound wave travels to and from the respective interfaces. A mode is used in echoencephalography for detection of midline shift and for localization of foreign bodies in the eye

B MODE IMAGING PRINCIPLE AND INSTRUMENTATION

In B mode imaging, the amplitude of the signal (echo strength) is represented by the brightness of a DOT. The A mode spike on CRT is converted into a DOT .The amplitude of the signal is represented by a DOT, the position of the DOT represents the depth of the interface from the transducer, but our interest is a 2 Dimensional image rather than acquiring signal from a single scan line which could be accomplished by Compound B scanning where in multiple set of dots are combined to delineate the echo pattern from internal structures within the body .There are two problems in B mode scanning which are not present in A mode is determination of transducer position and storage of the scan line information ,to overcome this problem the transducer is mounted on a scanning arm. If the detected echo signal is strong enough ,a positive charge region is created on the strong mesh which is behind the phosphorus screen of the CRT ,this would produce a bistable image where most of the internal organ details are lost so special system called scan converter are used for B mode imaging ,.Gray scale images enables different echo amplitude to be displayed in varying shades of gray so that fine internal structures of organs could be visualized ,the analog scan converter is similar to CRT except that the phosphor face is completely replaced by a wafer of silicon called the dielectric matrix. Another important characteristic of Scan converter is OVERWRITE –PROTECTOR CIRCUIT, each interface is scanned from many different orientation or direction during a B mode scan ,variety of signals are detected for each pixel depending on transducer orientation ,each time the signal is received ,the appropriate location in the scan converter is identified via sensor in the registration arm and the position generator .the system would add the new signal amplitude to the memory only if the new signal strength is higher than the previous

GATED MODE IMAGING PRINCIPLES AND INSTRUMENTATION

The difference in B mode and the C mode that is constant depth mode is a gating circuit ,In B mode all the echoes reflec ted back are taken where as in gated mode echoes only within specified interval of time is taken this is due to the gating circuit ,thus scan data obtained from a specific depth is displayed ,thus creating a plane of interest or a slice

ELECTRO CARDIOGRAPHY MODE

ECG –gated scanning is designed to reduce motion artifact obtained from static B mode scanning of the heart ,the position of the heart creates a blurred image because it is not at a constant position while acquiring image in B mode for this reason ECG acts as a gated circuit By selecting Q part of the wave as gating circuit an image of the heart at the beginning of the ventricular contraction is formed

In Real time gray scale scanner, the displayed image is continuously and rapidly updated with new scan data as the beam is swept repeatedly throughout the field view. .The increased use of Real time scanning is the result of advances in transducer technology.

In A mode the transducer is placed on the area of interest where ultrasound pulse last for 1micro sec and silent period is for about 999 microsec, the returning echoes are amplified and displayed .In B mode the transducer is placed at the starting position and information is recorded along the single line of sight, for a 2 dimensional image, transducer is manually moved by sonographer to a different position

ULTRASOUND BIRDS VIEW PART 1

Sound is a mechanical energy that is transmitted through a medium .The term MECHANICAL is defined as a physical change induced by a force, sound waves require elastic deformable medium for propagation .Ultrasound is defined as a high frequency mechanical wave that humans cannot hear with frequencies greater than 20K Hz. Waves are divided into two basic types :longitudinal and transverse, Ultrasound waves are longitudinal waves but only bone can cause production of transverse waves ,sometimes referred as shear waves or stress waves. Sound has a greater velocity in air (low density) than in bone (high density),Velocity is inversely proportional to the square root of the compressibility of the medium √B ,compressibility indicates the fractional decrease in volume when pressure is applied to the material, easier the medium to compress ,higher the compressibility, as bone is less compressible velocity of sound is more in bone .Reciprocal of compressibility is given by Bulk modulus, which means bulk modulus is directly proportional to velocity .As bulk modulus increases compressibility decreases in turn increases velocity of sound in the medium referring to this property as stiffness of medium The major interaction of interest for diagnostic ultrasound is that of reflection .if a sound beam is directed at right angles (normal incidence) to an interface (boundary between tissue type) larger than width of the sound beam, the beam is partially reflected back towards the sound source .the interface is called specular reflectors, and they are responsible for major organ outline seen in diagnostic ultrasound examination

The angle of reflection of the sound bean is equal to the angle of incidence of the sound beam. To obtain maximum reflected signal the transducer must be oriented so that the generated sound beam strikes the interface perpendicularly (normal incidence).to understand the concept of reflection of energy let us go back to basic physics of conservation of energy and conservation of momentum .conservation of energy would permit to transfer all its energy from one object to another, where as conservation of momentum prevents this due to differences in masses .Energy cannot be transmitted readily from large objects to small objects or from small objects to loarge subjects .If massive transfer of kinetic energy are required collision between objects of equal masses must occur .for sound waves which are a vibrating molecules ,they to behave in same manner ,as long as the molecule is transmitting energy to an identical sized molecule ,maximum transfer occurs .If there is a difference in the mass of the molecule ,less energy is transferred and the energy that is not transferred is reflected .In ultrasound ,the analogy to momentum is acoustic impedance .here ,one does not look at individual molecules ,but rather at their concerted action ,there by applying the concept of density.

Momentum (mechanics)=Mass × velocity Acoustic impedance( Ultrasound)= Density × Velocity

To simplify the term acoustic impedance I would say it is equal to resistance

High density materials give rise to high sound velocities and therefore high acoustic impedance, similarly low density materials such as gasses have low acoustic impedence .If acoustic impedence is the same in one medium as in another ,then the sound is readily transmitted from one medium to the other .a difference in acoustic impedance causes some portion of the sound to be reflected at the interface .this ist the main reason for ultrasound images .

The reflection coefficient for intensity is expressed as

α =(z2-z1/z2+z1)^2

α =reflection coefficient

z2 =impedance of medium 2

z1=impedance of medium1

The difference between two impedance subtracted any way and squared gives the same number, if acoustic impedance difference is small magnitude of the reflected wave is small. Bone is avoided during an ultrasound examination because acoustic impedance .As the difference between bone and tissue is very large most of the wave is reflected, little of the beam is transferred behind the bone and most of the incident beam returns to the detector, that is the reason why ultrasound is restricted to bony region .Thickness of the medium is never considered in calculation of reflection ,only impedance miss match is a point of concern

Another interaction that occurs between ultrasound and tissue is that of refraction .If the ultrasound beam strikes an interface between two media at an angle of 90 degree with respect to the surface ,a percentage of beam is reflected back to the first medium ,and the rest is transmitted into second medium without a change in direction ,if velocity of sound in both the medium will be equal then no refraction will occur although acoustic impedance may be different .For ultrasound image it is assumed that ultrasound beam always travel in straight lines through tissue .another important aspect is scattering and absorption ,all other modes of interaction except absorption decreases the ultrasonic beam intensity by redirecting the energy of the beam . Absorption is a process where in ultrasonic energy is transformed into another energy form, primarily heat which is used for physiotherapy .The absorption of the medium is related to frequency of beam ,viscosity of medium and relaxation time of the medium .If substances have a short relaxation time ,the molecules return to their original position before the next compression of wave arrives .however if the medium has a long relaxation time ,molecules may be moving back toward their original position as the wave crest strikes them ,more energy is required to stop and then reverse the direction of the molecule there by producing more heat

Saturday, July 30, 2011

Gene Therapy Unlocks Some Mysteries of Depression

The field of gene therapy can count another success, albeit a rather small one. Researchers at Weill Cornell Medical College were able to treat depressive behavior in a mouse model of depression using gene therapy techniques. The research also marks an advance in our understanding of the neurobiology of depression.

Dr. Kaplitt and colleagues created a mouse that expresses lower levels of a specific protein known as p11. The p11 protein promotes the activity serotonergic neurons in the brain, a longstanding target of depression treatment drugs such as SSRIs (selective serotonin reuptake inhibitors. This knockdown mouse displayed signs of depression when subjected to specific behavioral tests.

The way that they created the knockdown mouse was the interesting part. Researchers used an adeno-associated virus to “infect” or introduce a small-interfering RNA (siRNA) into a specific region of the brain called the nucleus accumbens. As a result, cells within this discrete brain region produced less of the p11 protein.

By using gene therapy to introduce this particular siRNA, the scientists were able to influence the behavior of the animal. Treated mice performed poorly on the forced swim test and the tail suspension test, which is consistent with depressive symptomatology. Curiously, when these siRNA treated mice were given antidepressant medications, their performance did not improve. Previous research showed that “depressed” mice (those that were stressed or postpartum) performing poorly of behavior tests would perform better if treated with an antidepressant. These results suggest that variations in human p11 may explain why some people do not experience a benefit from antidepressants.

The implications for human treatment are rather profound. The p11 protein appears to represent a newmolecular target for the development of depression treatments. Current treatment is focused on interfering with serotonin and norepinephrine reuptake. With a new target, pharmaceuticals or gene therapies could be developed to augment p11 expression.

Indeed, that is the immediate direction of future work. Studies are underway in non-human primates to use the adeno-associated virus to upregulate the levels of p11. The idea being that too little p11 not only underlies depression but also makes patients refractory to treatment. As with other avenues of gene therapy research, though, the road is long. A significant amount of efficacy and safety studies need to be performed before we see a gene therapy treatment of this nature in the clinic.

Thursday, July 21, 2011

PACE MAKER

As we call it by the name pace maker let us just why it is defined so … defining it… A pacemaker is a small electrical device that runs on a battery and produces low voltage rhythmic electrical signals that keep the heart beating when the heart's own electrical signals are deficient basically in a more simple way A pacemaker continuously "watches" the electrical system of heart and provides the needed electrical signal if the heart does not do so. During periods when the heart produces its own electrical signal normally, the pacemaker does nothing except to continue to monitor. So as it has to be placed within the body it has to be biocompatible, let me come to its biocompatibility a bit later before that lets see the basic part of the pacemaker .

A pacemaker system is made up of three main parts:

  • · The generator, a smooth, lightweight case containing a tiny computer and a battery which makes the electrical signals needed to pace the heart;
  • · The connector or header, which is the part of the generator where the leads are attached
  • · The leads, which are wires covered in soft, flexible plastic that are inserted into the heart to help the generator watch the heart and carry the generator’s signals to the heart.
A A pacemaker may have one or two leads. A pacemaker with one lead is called a single-chamber pacemaker. Where this one lead sits depends on where the signal problem in your heart is. A pacemaker with two leads is called a dual-chamber pacemaker. One lead usually sits in your right atrium, and the other usually sits in your right ventricle. Which type of pacemaker you need depends upon the kind of rhythm disturbance you have and your overall heart function. Depending on your situation, pacemaker will be used

Implanting the pacemaker

Toto implant the pacemaker there is a simple surgical procedure performed in the operating room or in the cardiac catheterization lab. When the decision to implant a pacemaker is made some prior instruction need to be followed

  • · Do not have anything to eat or drink for 6 hours before your procedure.
  • · If you are a diabetic you may be instructed to reduce or not take your insulin or other diabetic medicine on the day of the procedure to avoid low blood sugar.
  • You may be asked stop taking aspirin or other blood thinners several days prior to the procedure to avoid unnecessary bleeding

· Blood tests may be required on the day of the procedure or before it.

· Usually you will be asked to arrive in the hospital on the morning of the procedure several hours before the procedure so that you can be adequately prepared to undergo the surgery. After the procedure usual hospital stay is one day.

During the procedure

Immediately before your procedure, the skin area just beneath the shoulder and above the breast will be cleansed with special soap and may be shaved to remove excess hair. A mild sedative may be given to you to help you relax. The procedure may take 1 to 2 hours to complete. It is usually done under local anesthesia, which means that the area where the pacemaker will be inserted will be numbed with an injection. Subject should not feel any pain during the procedure, and should inform the doctor or staff if you are having pain so that more medication may be given. The most common insertion method is called endocardial (inside the heart) implantation. An incision is made in the skin under the collarbone and a "pocket" is formed under the skin and in front of the muscle in the upper chest for the pacemaker generator to rest in. The lead or leads are then threaded through a major vein in your upper chest and into your heart with the help of x-ray monitors. Their position inside your heart is determined by electrical measurements. Once the leads are in place, they are hooked to the generator, which is then inserted into the pocket that has been made. The pacemaker’s settings are programmed, the incision is closed, and a polybane sterile dressing is placed over the incision.. well some of us are not aware of sterile dressing …its composition is POLYMYXIN B SULPHATE U.S.P. 5000 UNITS and NEOMYCIN SULPHAT U.S.P. 3400 UNITS. It is sterilized by Gamma irradiation . A sterile dressing is a form of absorbent cotton fabric that is generally bonded on both sides so that it does not stick to the wound or area. It is used as wound care to promote the healing of an injury and to prevent more harm to the area. A sterile dressing is different from a bandage, in that a bandage is designed to hold a dressing in place while the sterile dressing is the antibacterial dressing Sterile dressings are designed with the idea that they will help the wound recover faster than doing nothing. They can stop bleeding and soak up prior fluid loss, help keep the wound free of infection and damage, and help in the healing of the wound.




Wednesday, June 29, 2011

GRADIENT COIL OF MRI

The ultimate goal of MRI is Image generation .The combination of static magnetic field and Radio frequency coils allows detection of MR signal but MR signal alone cannot be used to create an image .The fundamental measurement of MRI is merely the amount of current through a coil which in itself has no spatial information .Gradient coils provide the final touch up required for imaging .The main purpose of gradient coil is to cause MR signal spatially dependent in a controlled fashion. Gradient coils are generally turned off when Image acquisition is not required

To make the recovery of spatial information as simple as possible, gradient coils are used to generate a magnetic field that increases in strength along one spatial direction .The spatial direction used are relative to the main magnetic field, with Z axis parallel to main magnetic field and X and Y going perpendicularly to the main field .As previously gradient coils are evaluated on two criteria:: linearity and the field strength. The simplest example for gradient coil is MAXWELL pair. X and Y gradients are also called as Transverse Gradient both are created in the same fashion as Z, this transverse gradient changes the intensity of main field, and generally Golay pair is used is used .Strength of gradient coil is a function of both current density and the physical size of the coil

Monday, June 27, 2011

RADIO FREQUENCY COILS OF MRI

I had previously posted about static magnetic field this part the RADIO FREQUENCY COILS will continue the description of MRI ,hope you all will like it ,there could be typing error please correct it on the comment bar The static field does not produce any MR signal it is actually produced by use of two types of coils (transmitting coils )they are the transmitter and the receiver coils ,they generate and receive electromagnetic fields at the resonant frequency of the atomic nuclei within the static magnetic field ,this process gives the name resonance to magnetic resonance imaging. Because most atomic nuclei of interest for MRI studies have their resonant frequency in the radiofrequency portion of electromagnetic spectrum (at typical field strength of MRI),these coils are called radio frequency coils ,these coils can be evaluated on the same criteria as static field :uniformity and sensitivity .The radio frequency coils sends electromagnetic waves that resonate at a particular frequency ,as determined by the strength of magnetic field into the body ,disturbing the equilibrium state the process is known as excitation .When atomic nuclei are excited they absorb the energy of the radiofrequency pulse, But when the radiofrequency pulse ends the atomic nuclei go to equilibrium releasing energy absorbed during excitation ,this releasing energy are detected by the receiver coils the process is called as reception .The detected electromagnetic pulse defines raw MR signal

To explain it in a much simpler let me explain the way as I understood let me put it like this ,when I throw a ball in air I apply some potential energy to it by that I can give some energy to the ball ,now after the energy is lost the ball will come to equilibrium ,the energy present in the ball is given to the environment ,what happens in the atom is RF coils give potential energy and as the process of equilibrium is obtained the atom losses its energy to the surroundings ,here the difference with the ball and atom is we keep a receiver coil to extract all the energy i.e. the receiver coils the energy received depends on the distance from the sample being measured so the RF coils are generally placed immediately around the head in FMRI in both surface and volume coil arrangement. Now let me introduce you all to two other concepts of surface coil and volume coil. As I am from electrical background I would elaborate on this concept a bit more, as simple as possible The concept of surface coil begins with single loop (indicator-capacitor circuit) an additional resistance is also provided. As you all know that capacitor has a property of charging and discharging now when connected with an inductor due to rapid charge and discharge between capacitor and indicator it provides an oscillating current that can be tuned with the frequency of our interest, what happens here for the capacitor to charge we need a slow rising current which is accomplished by using an inductor what happens here to the total circuit is it will yield us a frequency which is f=1/2*(pi)*sqrt(L*C) by varying capacitance and inductance we can control the frequency ,it is similar to a radio receiver which uses similar circuit to receive station ,since receiver resonates at a particular frequency stations which are far off will not excite or give response ,the value of R should be small as possible so that only station is picked .In MRI the hydrogen atom will have a frequency which can be taken by the receiver coil ,the frequency adjustment is done by inductance and capacitance and Resistance should be small so that energy of only required area is captured .Because of close proximity towards brain surface coil it produces a high image sensitivity so it is generally used in FMRI to target one specific region of brain ,since the imaging depends on the distance from the surface coil ,whenever whole volume imaging is required it is inappropriate to use this

Now let us move to a second type of coil that is the volume coil which provides uniform spatial coverage throughout a large volume, the basic concept is that of surface coil (LC circuit) but here this LC circuit is replicated around a cylindrical surface to achieve uniform distribution of energy within the enclosed volume coil and sometimes referred as birdcage coil. As volume coil is father from the brain so sensitivity in the region of brain is less

A compromise approach has been made to get the best features of both the coil types, use volume coil for exiting and surface coil for receiving the MR signal .if multiple receiver coils is used arranged in a overlapping pattern known as phased array. Sensitivity of radiofrequency coil is proportional to strength of magnetic field generated within the coil by unit current. To obtain quantitative measurement of coil sensitivity, Quality factor is defined as ratio of maximum energy stored and total energy dissipated per period

Quality factor (Q)=sqrt(INDUCTANCE)/RESISTANCE*sqrt(CAPACITANCE)

Minimizing resistance will boost coil sensitivity

Saturday, June 25, 2011

mineSweeper game run using matlab

function mineSweeper(varargin);

%
%The game is probably familiar to everyone, but the game has a slight
%twist. You may play the game such that there may be up to 7 mines per
%square instead of just one.
%
%Left click:
% - If the square is not a mine then a number will appear counting the
% number of mines in the uncovered surrounding squares.
%
% - If the square is a mine, the game is over.
%
% - If the square was already uncovered, and all the flags have been set,
% then it will uncover the surrounding squares - however, if any of
% those are actually a mine, the game is over.
%
% - If the square was flagged, one flag will be removed.
%
%Right click:
% - Set and cycle through the flags, each right click will add another
% flag.
%
% - To clear all the flags from the square, continue to right click and
% cycle back to the reset position. (Or, left click down to 0 flags.)
%
% - If the square was uncovered, nothing will happen.

%
%% Initial set up

%Change MATLAB's rand state
rand('twister',sum(100*clock));

%Number of board columns
gameBoard.gameCols = 30;
%Number of board rows
gameBoard.gameRows = 16;
gameBoard.numberBoxes = gameBoard.gameRows * gameBoard.gameCols;
%Maximum number of mines per square, default value of 1 if not set
gameBoard.maxMines = 1;
if nargin == 1;
gameBoard.maxMines = varargin{1};
if ischar(gameBoard.maxMines);%Surprise me
gameBoard.maxMines = ceil(7 * rand);
end;
end;

%Initial mine distribution matrix, each column represents a maxMines
%value and each row represents the number of mines to be placed on the
%board
mineDistribution = [...
100,60,50,40,40,35,30;...
0, 40,30,30,24,25,24;...
0, 0, 20,20,18,16,18;...
0, 0, 0, 10,12,11,12;...
0, 0, 0, 0, 6, 8, 8;...
0, 0, 0, 0, 0, 5, 5;...
0, 0, 0, 0, 0, 0, 3];

%Initial distribution vector for the case we will play
mineDistribution = mineDistribution(:,gameBoard.maxMines);

%Will be used later to determine the number of flags left to mark
flagsLeft = 0 * mineDistribution;

%gameBoard will hold the user clicks and the state of the board:
%The first page:
%0 means covered, 1 means uncovered, -X means X flags set
%The second page:
%The handles to the text representing the flags set
%The third page:
%The handles to the boxes drawn
%The fourth page:
%The mine values
temp = zeros(gameBoard.gameRows,gameBoard.gameCols);
gameBoard.mineValues = temp;
gameBoard.boxHandles = temp;
gameBoard.flagHandle = temp;
gameBoard.userClicks = temp;

%% Create game board display

%Create figure
gameHandle = figure;
figColor = [0.80 0.80 0.80];
set(gameHandle,'Units','Normalized',...
'Position',[0.15 0.20 0.70 0.50],...
'Color',figColor,...
'Name','Mine Sweeper',...
'NumberTitle','Off',...
'Resize','Off');

%Add game menu
set(gameHandle,'MenuBar','None');
menuHandle = uimenu('Label','Start New Game');
uimenu(menuHandle,'Label','At most 1 mine,',...
'Callback','closereq;mineSweeper(1);','Accelerator','1');
uimenu(menuHandle,'Label','At most 2 mines,',...
'Callback','closereq;mineSweeper(2);','Accelerator','2');
uimenu(menuHandle,'Label','At most 3 mines,',...
'Callback','closereq;mineSweeper(3);','Accelerator','3');
uimenu(menuHandle,'Label','At most 4 mines,',...
'Callback','closereq;mineSweeper(4);','Accelerator','4');
uimenu(menuHandle,'Label','At most 5 mines,',...
'Callback','closereq;mineSweeper(5);','Accelerator','5');
uimenu(menuHandle,'Label','At most 6 mines,',...
'Callback','closereq;mineSweeper(6);','Accelerator','6');
uimenu(menuHandle,'Label','At most 7 mines,',...
'Callback','closereq;mineSweeper(7);','Accelerator','7');
uimenu(menuHandle,'Label','Surprise me,',...
'Callback','closereq;mineSweeper(''s'');','Accelerator','S');
uimenu(menuHandle,'Label','End game,',...
'Callback','closereq;','Accelerator','Q');

%Add box to count number of flags remaining
flagHandle = uicontrol(gameHandle,'Style','text');
set(flagHandle,'Units','Normalized',...
'Position',[0.02 0.55 0.14 0.40],...
'BackgroundColor',figColor);

%Add message dialog box
talkHandle = uicontrol(gameHandle,'Style','text');
set(talkHandle,'Units','Normalized',...
'Position',[0.02 0.35 0.14 0.10],...
'BackgroundColor',figColor,...
'String','Good luck!','FontSize',16);

%Add game board axes
axisHandle = axes;
set(axisHandle,'Units','Normalized',...
'Position',[0.18 0.05 0.80 0.90],...
'XLim',[0 gameBoard.gameCols],'YLim',[0 gameBoard.gameRows],...
'YDir','Reverse',...
'XTick',[],'YTick',[],'Box','On');

%% Create game board values

%The indices into the board which contain a mine will be randomly
%selected using randperm
gameBoardIndex = randperm(gameBoard.numberBoxes);
mineCumulative = cumsum(mineDistribution);

%Set the first set as containing one mine
gameBoard.mineValues(gameBoardIndex(1:mineCumulative)) = -1;

%Loop through remaining random spots for next mine increment
for dMine = 2:gameBoard.maxMines;
gameBoard.mineValues(gameBoardIndex...
(mineCumulative(dMine - 1) + 1:mineCumulative(dMine))) = -dMine;
end;

%For each non-mine position, need to count the number of mines around,
%start by computing all the rows and columns
[dIndexRow,dIndexCol] = ind2sub...
([gameBoard.gameRows gameBoard.gameCols],...
1:gameBoard.numberBoxes);
dIndexRow = repmat(dIndexRow',[1 3]);
dIndexCol = repmat(dIndexCol',[1 3]);
%The rows and columns that surround are +/- 1 from the middle
surroundingPoints = repmat([-1 0 1],[size(dIndexRow,1),1]);
dIndexRow = dIndexRow + surroundingPoints;
dIndexCol = dIndexCol + surroundingPoints;

for dIndex = 1:gameBoard.numberBoxes;
if gameBoard.mineValues(dIndex) < 0;
%Nothing to count, index is flagged
continue;
end;
%Find the surrounding squares
surroundingIndices = surroundingSquares(...
dIndexRow(dIndex,:),gameBoard.gameRows,...
dIndexCol(dIndex,:),gameBoard.gameCols);

%Find these gameBoard values
temp = gameBoard.mineValues(surroundingIndices);
%Only count the flags (negative values)
k = temp < 0;
%Sum the number of flags surrounding this index
gameBoard.mineValues(dIndex) = abs(sum(sum(temp .* k)));
end;

%Display the game board in the background of the figure
gameBoard.xOffset = -0.75;%Offset from edge of row/col
gameBoard.yOffset = -0.50;%Offset from edge of row/col
[x,y] = meshgrid(...
1 + gameBoard.xOffset:1:gameBoard.gameCols + gameBoard.xOffset,...
1 + gameBoard.yOffset:1:gameBoard.gameRows + gameBoard.yOffset);

%Display text
textHandles = text(x(:),y(:),int2str(gameBoard.mineValues(:)),...
'FontSize',8);
set(textHandles,'Color',[0.00 0.00 1.00]);
%The 0 values should not display, and mines are to be colored red
k = gameBoard.mineValues(:);
set(textHandles(k == 0),'Visible','Off');
set(textHandles(k < 0),'Color',[1.00 0.00 0.00]);

%Now, cover the number of mines (otherwise the game would be pointless)
gameBoard.uncoveredColor = [0.40 0.40 0.40];%dark gray covering square
gameBoard.markedColor = [1.00 1.00 0.50];%yellow indicating flagged
%For each grid point, create a patch of a box covering the area
for dRow = 0:gameBoard.gameRows - 1;
for dCol = 0:gameBoard.gameCols - 1;
gameBoard.boxHandles(dRow + 1,dCol + 1) = patch(...
[dCol, dCol, dCol + 1, dCol + 1, dCol],...
[dRow, dRow + 1, dRow + 1, dRow, dRow],...
gameBoard.uncoveredColor);
set(gameBoard.boxHandles(dRow + 1,dCol + 1),...
'EdgeColor',[0.00 0.00 0.00]);
end;
end;

%Setup the text containing the flag information
flagsLeftString = char(zeros(gameBoard.maxMines,6));
for dMine = 1:gameBoard.maxMines;
switch dMine;
case 1;
flagsLeftString(dMine,:) = ' I - ';
case 2;
flagsLeftString(dMine,:) = 'II - ';
case 3;
flagsLeftString(dMine,:) = 'III - ';
case 4;
flagsLeftString(dMine,:) = 'IV - ';
case 5;
flagsLeftString(dMine,:) = ' V - ';
case 6;
flagsLeftString(dMine,:) = 'VI - ';
case 7;
flagsLeftString(dMine,:) = 'VII - ';
end;
end;

%% Play game
gameContinues = true;
gameWon = false;

while gameContinues;

%Update mine count
for dMine = 1:gameBoard.maxMines;
flagsLeft(dMine,1) = mineDistribution(dMine) -...
sum(sum(gameBoard.userClicks == -dMine));
end;
set(flagHandle,...
'String',[flagsLeftString,...
int2str(flagsLeft(1:gameBoard.maxMines))],'FontSize',12);

%Determine if game has been won
k = gameBoard.mineValues < 0;
if all(all(gameBoard.mineValues(k) == gameBoard.userClicks(k))) &&...
all(all(gameBoard.userClicks(~k) == 1));
%All flags set and match the mine value, and all boxes uncovered
gameContinues = false;
gameWon = true;
continue;
end;

%Get user click
try;
m = waitforbuttonpress;
if m == 1;
continue;
end;
catch;
%User closed game
return;
end;

%Return mouse position
thisPoint = get(axisHandle,'CurrentPoint');
thisRow = floor(thisPoint(1,2)) + 1;
thisCol = floor(thisPoint(1,1)) + 1;
%Return mouse button used
thisButton = get(gameHandle,'SelectionType');

if thisRow <= 0 || thisRow > gameBoard.gameRows ||...
thisCol <= 0 || thisCol > gameBoard.gameCols;
%Clicked outside the board, try again
continue;
end;

switch thisButton;
case 'normal';%Left button

%Square has a flag on it, left click void
if gameBoard.userClicks(thisRow,thisCol) < 0;
gameBoard.userClicks(thisRow,thisCol) =...
gameBoard.userClicks(thisRow,thisCol) + 1;
%Place/update flag on board
gameBoard = setFlag(gameBoard,thisRow,thisCol);
continue;
end;

%Square was not clear, but is a mine
if gameBoard.mineValues(thisRow,thisCol) < 0 &&...
gameBoard.userClicks(thisRow,thisCol) == 0;
%Oops, stepped on a mine
set(gameBoard.boxHandles(thisRow,thisCol),...
'FaceColor','None');
gameContinues = false;
continue;
end;

%Square was not clear, not a mine
if gameBoard.mineValues(thisRow,thisCol) >= 0 &&...
gameBoard.userClicks(thisRow,thisCol) == 0;
set(gameBoard.boxHandles(thisRow,thisCol),...
'FaceColor','None');
gameBoard.userClicks(thisRow,thisCol) = 1;
newlyUncovered = sub2ind...
([gameBoard.gameRows gameBoard.gameCols],...
thisRow,thisCol);
end;

%Square clear, number of flags set, clear surrounding area
surroundingIndices = surroundingSquares(...
thisRow,gameBoard.gameRows,...
thisCol,gameBoard.gameCols);

temp = gameBoard.userClicks(surroundingIndices);
k = temp < 0;
flagsSet = abs(sum(sum(temp .* k)));

if flagsSet == gameBoard.mineValues(thisRow,thisCol) &&...
flagsSet > 0 &&...
gameBoard.userClicks(thisRow,thisCol) == 1;
%Find all surrounding points that aren't flagged
k = gameBoard.userClicks(surroundingIndices) < 0;
set(gameBoard.boxHandles(surroundingIndices(~k)),...
'FaceColor','None');
gameBoard.userClicks(surroundingIndices(~k)) = 1;
newlyUncovered = surroundingIndices(~k);
if any(gameBoard.mineValues(surroundingIndices(~k)) < 0);
%Oops, set a flag incorrectly and uncovered a mine
gameContinues = false;
continue;
end;
end;

%Call a recursive function to uncover all the connected 0
%values, this will happen if the square was a 0 or if the
%flags were set and a 0 was uncovered
[newlyUncovered,gameBoard] = uncoverZeros...
(newlyUncovered,gameBoard,[]);

case 'alt';%Right button

%Box already cleared, right click void
if gameBoard.userClicks(thisRow,thisCol) == 1;
continue;
end;

%Mark flag, subtract 1 to mean another flag added
gameBoard.userClicks(thisRow,thisCol) =...
gameBoard.userClicks(thisRow,thisCol) - 1;

%Place/update flag on board
gameBoard = setFlag(gameBoard,thisRow,thisCol);
end;
end;

%Game over, display end game message
if gameWon;
newColor = [0.30 0.30 1.00];
set(talkHandle,'String','Well Done!');
else;
newColor = [1.00 0.50 0.00];
set(talkHandle,'String',' O O P S! ');
%Display flags set incorrectly
k = gameBoard.userClicks < 0 &...
gameBoard.mineValues ~= gameBoard.userClicks;
set(gameBoard.boxHandles(k),'FaceColor',[1.00 0.00 0.00]);
%Display mines not flagged
k = gameBoard.mineValues < 0 & gameBoard.userClicks >= 0;
set(gameBoard.boxHandles(k),'FaceColor','None');
end;
set(gameHandle,'Color',newColor);
set(flagHandle,'BackgroundColor',newColor);
set(talkHandle,'BackgroundColor',newColor);

end

%% Set Flags

%Function to place/update the correct flag on the board
function gameBoard = setFlag(gameBoard,thisRow,thisCol);

%Use mod arithmetic only
temp = mod(-gameBoard.userClicks(thisRow,thisCol),...
gameBoard.maxMines + 1);
gameBoard.userClicks(thisRow,thisCol) = -temp;
%If text has previously been set...
if gameBoard.flagHandle(thisRow,thisCol) ~= 0;
%...Clear flag string
set(gameBoard.flagHandle(thisRow,thisCol),'String','');
end;
%Set square color to indicate it is marked
thisColor = gameBoard.markedColor;
switch temp;%Number of flags set
case 0;%Reset square to uncovered state
flagString = '';
thisColor = gameBoard.uncoveredColor;
case 1;
flagString = ' I ';
case 2;
flagString = ' I I ';
case 3;
flagString = 'I I I';
case 4;
flagString = 'I V ';
case 5;
flagString = ' V ';
case 6;
flagString = 'V I ';
case 7;
flagString = 'VI I';
end;
%Display flags, set square color
gameBoard.flagHandle(thisRow,thisCol) =...
text(thisCol + gameBoard.xOffset,thisRow + gameBoard.yOffset,...
flagString,'FontName','Arial','FontSize',6);
set(gameBoard.boxHandles(thisRow,thisCol),...
'FaceColor',thisColor);

end

%% Surrounding Squares Indices

%Return the indices surrounding the current square(s)
function surroundingIndices = surroundingSquares(rowIndices,gameRows,...
colIndices,gameCols);

if length(rowIndices) == 1;
rowIndices = rowIndices + [-1 0 1];
end;
if length(colIndices) == 1;
colIndices = colIndices + [-1 0 1];
end;

%For one index at a time, determine the rows and columns that
%surround the index, removing those off the game board.
m = ~(rowIndices <= 0 | rowIndices > gameRows);
n = ~(colIndices <= 0 | colIndices > gameCols);
%Compute the "all-possible" pairings of rows and columns
[surroundingRows,surroundingCols] = meshgrid...
(rowIndices(m),colIndices(n));
%Easier to use indices
surroundingIndices = sub2ind...
([gameRows gameCols],surroundingRows,surroundingCols);

end

%% Uncover 0 Squares

%Recursive function to uncover squares with a 0 value
function [newlyUncovered,gameBoard] =...
uncoverZeros(newlyUncovered,gameBoard,alreadyCleared);

%Game size
[gameRows,gameCols] = size(gameBoard.mineValues);

%Keep only the new squares that are a 0
newlyUncovered = newlyUncovered...
(gameBoard.mineValues(newlyUncovered) == 0);

while ~isempty(newlyUncovered);
%Take the first index
[rowIndex,colIndex] = ind2sub...
([gameRows gameCols],newlyUncovered(1));
%Return all points the surround this square
temp = surroundingSquares(rowIndex,gameRows,colIndex,gameCols);

%Add to a list of squares already dealt with to avoid an infinite
%recursion
alreadyCleared = unique([alreadyCleared;newlyUncovered(1)]);

%Remove squares marked as already clear
temp = setdiff(temp(:),alreadyCleared);
%Remove point currently being cleared
newlyUncovered(1) = [];
%Add the surrounding squares to this list
newlyUncovered = unique([newlyUncovered;temp(:)]);

%If the user set a 0 as a flag don't uncover
temp = temp(gameBoard.userClicks(temp) >= 0);

%Mark these squares as cleared
gameBoard.userClicks(temp) = 1;
set(gameBoard.boxHandles(temp),'FaceColor','None');

%Recursive call, will continue until the trail of 0s has been
%uncovered
[newlyUncovered,gameBoard] = uncoverZeros...
(newlyUncovered,gameBoard,alreadyCleared);
end;

end