/****************************

AUTHOR: MIROSLAV MURIN

*****************************/


package mrecorder.diodegames.eu;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Frame;
import java.awt.Graphics2D;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import javax.imageio.stream.ImageOutputStream;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.TargetDataLine;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import com.xuggle.mediatool.IMediaWriter;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.xuggler.ICodec;


public class Main extends JFrame {

	AudioFormat audioFormat, mixerformat;
	TargetDataLine targetDataLine, mixerdataline;

	private static final long serialVersionUID = 4244558037467209113L;

	Rectangle screens = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
	Robot robot, robot2;

	JPanel panel;

	int numofph = 0, gt = 0, bug = 0;

	Timer timer = new Timer();

	boolean small = false, recording = false, fpss = false, cansn = false, click = false;

	JButton start, video, videon, videow;
	JCheckBox lowq = new JCheckBox();
	JCheckBox fps = new JCheckBox();
	JCheckBox tmprmv = new JCheckBox();
	JCheckBox audioc = new JCheckBox();
	JLabel warn;

	boolean stopped = false;




	ByteArrayOutputStream buffer = new ByteArrayOutputStream();



	File toWrite;


	long lasttime = System.currentTimeMillis();

	String absolutePath = System.getProperty("user.dir");

	static public boolean deleteDirectory(File path) {
		if (path.exists()) {
			File[] files = path.listFiles();
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					deleteDirectory(files[i]);
				} else {
					files[i].delete();
				}
			}
		}
		return (path.delete());
	}



	//**************** THREAD TAKESNAPSHOT
	public void takesnth() {



		new Thread(new Runnable()

		{

			public void run()

			{
				bug++;

				BufferedImage image = robot2.createScreenCapture(screens);


				if (small) {
					int newW = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth() / 2;
					int newH = (int) Toolkit.getDefaultToolkit().getScreenSize().getHeight() / 2;
					Image tmp = image.getScaledInstance(newW, newH, Image.SCALE_SMOOTH);
					BufferedImage dimg = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);

					Graphics2D g2d = dimg.createGraphics();
					g2d.drawImage(tmp, 0, 0, null);
					g2d.dispose();
					image = dimg;
				}


				try {
					ImageIO.write(image, "jpg", new File("temp/screenshot" + numofph + ".jpg"));
					numofph++;
					bug = 0;

				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}



			}

		}).start();

	}


	//********************* MAIN ***************************
	public Main() {



		super("Screen Recorder M");
		setSize(400, 400);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setResizable(false);
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		this.setLocation(dim.width / 2 - this.getSize().width / 2, dim.height / 2 - this.getSize().height / 2);


		timer.schedule(new takesnap(), 30, 30);
		setVisible(true);



		PrintStream out = null;
		try {
			out = new PrintStream(new FileOutputStream("output.txt"));
			System.setOut(out);

		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.out.println("Error:" + e1.getMessage());
		}




		BufferedImage imagei = null;
		try {
			imagei = ImageIO.read(Main.class.getResourceAsStream("/icon.png"));
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.out.println("Error:" + e1.getMessage());
		}

		setIconImage(imagei);

		System.out.println("path:" + System.getProperty("user.dir"));


		File f = new File("temp");
		if (f.exists() && f.isDirectory()) {
			System.out.println("Exist");
			deleteDirectory(new File("temp"));


			boolean success = (

			new File("temp")).mkdir();
			if (success) {
				System.out.println("Directory: temp created");
			}

		} else {

			boolean success = (

			new File("temp")).mkdir();
			if (success) {
				System.out.println("Directory: temp created");
			}
		}



		File fs = new File("temp");
		if (fs.exists() && fs.isDirectory()) {
			System.out.println("Exist2");
		} else {

			boolean success = (

			new File("temp")).mkdir();
			if (success) {
				System.out.println("Directory: temp created");
			}
		}




		try {
			robot = new Robot();
		} catch (AWTException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		try {
			robot2 = new Robot();
		} catch (AWTException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}




		panel = new JPanel();

		Color mycol = new Color(255, 210, 0);
		panel.setBackground(mycol);

		getContentPane().add(panel);

		panel.setLayout(null);

		warn = new JLabel("");
		warn.setBounds(10, 50, 400, 40);
		warn.setForeground(Color.red);

		JLabel nadpis;
		nadpis = new JLabel("Screen Recorder M");
		nadpis.setBounds(10, 0, 400, 40);
		nadpis.setForeground(Color.blue);

		InputStream is = Main.class.getResourceAsStream("/fontd.ttf");
		Font font = null;
		try {
			font = Font.createFont(Font.TRUETYPE_FONT, is);
		} catch (FontFormatException | IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		GraphicsEnvironment genv = GraphicsEnvironment.getLocalGraphicsEnvironment();
		genv.registerFont(font);


		font = font.deriveFont(50f);

		nadpis.setFont(font);



		JLabel author;
		author = new JLabel("Miroslav Murin  Twitter: @Miro382    V1.0");
		author.setBounds(10, 290, 400, 40);
		author.setForeground(Color.blue);

		JButton visit;
		visit = new JButton("Visit");
		visit.setBounds(280, 280, 80, 40);
		visit.setToolTipText("Start recording");
		visit.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {

				try {
					Desktop.getDesktop().browse(new URL("http://shop.diodegames.eu/mrecorder.html").toURI());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});



		JButton gif;
		gif = new JButton("Create GIF");
		gif.setBounds(10, 100, 150, 80);
		gif.setToolTipText("Create GIF from record");
		gif.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {

				warn.setText("Please wait... Record is still creating...");
				panel.revalidate();
				panel.repaint();

				Thread t = new Thread(new Runnable() {@Override
					public void run() {
						if (!click) {
							click = true;
							creategif();
							numofph = 0;
							panel.add(start);
							panel.add(author);
							panel.add(visit);
							panel.add(lowq);
							panel.add(audioc);
							panel.add(fps);
							panel.remove(gif);
							panel.remove(video);
							panel.remove(tmprmv);
							panel.remove(videon);
							panel.revalidate();
							panel.repaint();
						}
					}
				});
				t.start();



			}
		});


		video = new JButton("Create Video .mp4");
		video.setBounds(10, 190, 150, 80);
		video.setToolTipText("Create mp4 (Codec MPEG4) Video from record");
		video.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {

				warn.setText("Please wait... Record is still creating...");
				panel.revalidate();
				panel.repaint();

				Thread t = new Thread(new Runnable() {@Override
					public void run() {
						if (!click) {
							click = true;
							createvideo();
							//vimage = new BufferedImage[9999999];
							numofph = 0;
							panel.add(start);
							panel.add(lowq);
							panel.add(author);
							panel.add(visit);
							panel.add(fps);
							panel.add(audioc);
							panel.remove(gif);
							panel.remove(video);
							panel.remove(videow);
							panel.remove(tmprmv);
							panel.remove(videon);
							panel.revalidate();
							panel.repaint();
						}
					}
				});
				t.start();



			}
		});

		videon = new JButton("Create Video H264");
		videon.setBounds(170, 100, 150, 80);
		videon.setToolTipText("Create Video (Codec H264) from record");
		videon.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {

				warn.setText("Please wait... Record is still creating...");
				panel.revalidate();
				panel.repaint();

				Thread t = new Thread(new Runnable() {@Override
					public void run() {
						if (!click) {
							click = true;
							createvideoh264();
							//vimage = new BufferedImage[9999999];
							numofph = 0;
							panel.add(start);
							panel.add(lowq);
							panel.add(fps);
							panel.add(author);
							panel.add(visit);
							panel.add(audioc);
							panel.remove(gif);
							panel.remove(video);
							panel.remove(videow);
							panel.remove(videon);
							panel.remove(tmprmv);
							panel.revalidate();
							panel.repaint();
						}
					}
				});
				t.start();



			}
		});





		videow = new JButton("Create Video WMV");
		videow.setBounds(170, 190, 150, 80);
		videow.setToolTipText("Create Video wmv (WMV2) from record");
		videow.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {

				warn.setText("Please wait... Record is still creating...");
				panel.revalidate();
				panel.repaint();

				Thread t = new Thread(new Runnable() {@Override
					public void run() {
						if (!click) {
							click = true;
							createvideowmv();
							//vimage = new BufferedImage[9999999];
							numofph = 0;
							panel.add(start);
							panel.add(lowq);
							panel.add(fps);
							panel.add(author);
							panel.add(visit);
							panel.add(audioc);
							panel.remove(gif);
							panel.remove(video);
							panel.remove(videon);
							panel.remove(tmprmv);
							panel.remove(videow);
							panel.revalidate();
							panel.repaint();
						}
					}
				});
				t.start();



			}
		});





		JButton stop;
		stop = new JButton("Stop");
		stop.setBounds(100, 120, 200, 100);
		stop.setToolTipText("Stop video");
		stop.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {

				if (audioc.isSelected()) {
					targetDataLine.stop();
					targetDataLine.close();
				}

				stopped = true;
				recording = false;
				panel.remove(stop);
				panel.add(gif);
				panel.add(video);
				panel.add(videow);
				panel.add(videon);
				panel.add(tmprmv);
				warn.setText("Set how you want save the record.");
				panel.revalidate();
				panel.repaint();
			}
		});


		tmprmv.setText("Remove backup");
		tmprmv.setBackground(mycol);
		tmprmv.setBounds(10, 330, 120, 30);
		tmprmv.setToolTipText("Delete backup, when the software completes its work");


		lowq.setText("Low Quality");
		lowq.setBackground(mycol);
		lowq.setBounds(10, 330, 100, 30);
		lowq.setToolTipText("Video will be in low quality");



		fps.setText("More FPS");
		fps.setBackground(mycol);
		fps.setBounds(120, 330, 90, 30);
		fps.setToolTipText("Video will be bigger, but will have more frames");

		audioc.setText("Record microphone");
		audioc.setBackground(mycol);
		audioc.setBounds(220, 330, 150, 30);
		audioc.setToolTipText("Record microphone? You must have microphone");






		start = new JButton("Start");
		start.setBounds(100, 120, 200, 100);
		start.setToolTipText("Start recording");
		start.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent event) {

				click = false;
				bug = 0;


				File fs = new File("temp");
				if (fs.exists() && fs.isDirectory()) {
					System.out.println("Exist - start button");
				} else {

					boolean success = (

					new File("temp")).mkdir();
					if (success) {
						System.out.println("Directory: temp created");
					}
				}

				if (audioc.isSelected()) captureaudio();


				if (lowq.isSelected()) small = true;
				else small = false;

				if (fps.isSelected()) {
					fpss = true;
				} else {
					fpss = false;
				}


				panel.add(stop);
				panel.remove(lowq);
				panel.remove(audioc);
				panel.remove(fps);
				panel.remove(author);
				panel.remove(visit);
				panel.remove(start);
				warn.setText("Recording...");
				panel.revalidate();
				panel.repaint();
				recording = true;
				setState(Frame.ICONIFIED);
			}
		});





		panel.add(nadpis);
		panel.add(start);
		panel.add(warn);
		panel.add(lowq);
		panel.add(fps);
		panel.add(audioc);
		panel.add(visit);
		panel.add(author);
		//  panel.add(stop); 

		panel.revalidate();
		panel.repaint();

	}







	//******************* TIMER TAKESNAPSHOT ************************//
	class takesnap extends TimerTask {
		public void run() {



			if (recording) {
				gt++;

				if (fpss) {
					gt = 0;
					cansn = true;
				} else {
					if (gt > 1) {
						gt = 0;
						cansn = true;
					}

				}


				if (cansn) {



					if (bug > 10) {
						setState(Frame.NORMAL);
						warn.setText("Something is bad !!! :(");

						String message = "Something is bad !!! :(";
						JOptionPane.showMessageDialog(new JFrame(), message, "Error",
						JOptionPane.ERROR_MESSAGE);
						panel.revalidate();
						panel.repaint();
					}



					cansn = false;
					takesnth();




				} //cansn
			} //recording

		} //runtask
	} //runtask class









	private static Dimension screenBounds;



	public static BufferedImage convertToType(BufferedImage sourceImage, int targetType) {

		BufferedImage image;

		// if the source image is already the target type, return the source image
		if (sourceImage.getType() == targetType) {
			image = sourceImage;
		}
		// otherwise create a new image of the target type and draw the new image
		else {
			image = new BufferedImage(sourceImage.getWidth(),
			sourceImage.getHeight(), targetType);
			image.getGraphics().drawImage(sourceImage, 0, 0, null);
		}

		return image;

	}


	void createvideo() {
		String outputFilename = "video" + UUID.randomUUID() + ".mp4";
		System.out.println("Creating video started - 1");

		System.out.println("Created frames - 4  Number of frames:" + numofph);

		final IMediaWriter writer = ToolFactory.makeWriter(outputFilename);
		System.out.println("Video Writer started - 2");
		screenBounds = Toolkit.getDefaultToolkit().getScreenSize();


		if (small) writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_MPEG4,
		screenBounds.width / 2, screenBounds.height / 2);
		else writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_MPEG4,
		screenBounds.width, screenBounds.height);


		System.out.println("Video Setting - 3");

		int timeall = 0;

		for (int index = 0; index < numofph; index++) {


			Image image = null;
			try {
				File f = new File("temp/screenshot" + index + ".jpg");
				if (f.exists() && !f.isDirectory()) {
					image = ImageIO.read(new File("temp/screenshot" + index + ".jpg"));
					timeall++;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (image != null) {
				BufferedImage screen;
				screen = (BufferedImage) image;

				// convert to the right image type
				BufferedImage bgrScreen = convertToType(screen,
				BufferedImage.TYPE_3BYTE_BGR);


				if (fpss) writer.encodeVideo(0, bgrScreen, 30 * timeall,
				TimeUnit.MILLISECONDS);
				else writer.encodeVideo(0, bgrScreen, 60 * timeall,
				TimeUnit.MILLISECONDS);
			}



		}

		System.out.println("Created frames - 4");

		writer.close();



		System.out.println("Video Created - 5 Works");
		warn.setText("Success");
		click = false;
		if (tmprmv.isSelected()) {
			deleteDirectory(new File("temp"));

			boolean success = (

			new File("temp")).mkdir();
			if (success) {
				System.out.println("Directory: temp created");
			}
		}


	}








	void createvideoh264() {
		String outputFilename = "video" + UUID.randomUUID() + ".mp4";
		System.out.println("Creating video started - 1");

		System.out.println("Created frames - 4  Number of frames:" + numofph);

		final IMediaWriter writer = ToolFactory.makeWriter(outputFilename);
		System.out.println("Video Writer started - 2");
		screenBounds = Toolkit.getDefaultToolkit().getScreenSize();

		// We tell it we're going to add one video stream, with id 0,
		// at position 0, and that it will have a fixed frame rate of FRAME_RATE.

		if (small) writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_H264,
		screenBounds.width / 2, screenBounds.height / 2);
		else writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_H264,
		screenBounds.width, screenBounds.height);




		System.out.println("Video Setting - 3");

		int timeall = 0;

		for (int index = 0; index < numofph; index++) {


			Image image = null;
			try {
				File f = new File("temp/screenshot" + index + ".jpg");
				if (f.exists() && !f.isDirectory()) {
					image = ImageIO.read(new File("temp/screenshot" + index + ".jpg"));
					timeall++;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (image != null) {
				BufferedImage screen;
				screen = (BufferedImage) image;

				// convert to the right image type
				BufferedImage bgrScreen = convertToType(screen,
				BufferedImage.TYPE_3BYTE_BGR);


				if (fpss) writer.encodeVideo(0, bgrScreen, 30 * timeall,
				TimeUnit.MILLISECONDS);
				else writer.encodeVideo(0, bgrScreen, 60 * timeall,
				TimeUnit.MILLISECONDS);
			}


			// sleep for frame rate milliseconds

		}

		System.out.println("Created frames - 4");

		// tell the writer to close and write the trailer if  needed
		writer.close();

		System.out.println("Video Created - 5 Works");
		warn.setText("Success");
		click = false;
		if (tmprmv.isSelected()) {
			deleteDirectory(new File("temp"));

			boolean success = (

			new File("temp")).mkdir();
			if (success) {
				System.out.println("Directory: temp created");
			}
		}


	}











	void createvideowmv() {
		String outputFilename = "video" + UUID.randomUUID() + ".wmv";
		System.out.println("Creating video started - 1");

		System.out.println("Created frames - 4  Number of frames:" + numofph);

		final IMediaWriter writer = ToolFactory.makeWriter(outputFilename);
		System.out.println("Video Writer started - 2");
		screenBounds = Toolkit.getDefaultToolkit().getScreenSize();

		// We tell it we're going to add one video stream, with id 0,
		// at position 0, and that it will have a fixed frame rate of FRAME_RATE.
		//qtrle
		if (small) writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_WMV2,
		screenBounds.width / 2, screenBounds.height / 2);
		else writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_WMV2,
		screenBounds.width, screenBounds.height);




		System.out.println("Video Setting - 3");

		int timeall = 0;

		for (int index = 0; index < numofph; index++) {


			Image image = null;
			try {
				File f = new File("temp/screenshot" + index + ".jpg");
				if (f.exists() && !f.isDirectory()) {
					image = ImageIO.read(new File("temp/screenshot" + index + ".jpg"));
					timeall++;
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (image != null) {
				BufferedImage screen;
				screen = (BufferedImage) image;

				// convert to the right image type
				BufferedImage bgrScreen = convertToType(screen,
				BufferedImage.TYPE_3BYTE_BGR);


				if (fpss) writer.encodeVideo(0, bgrScreen, 30 * timeall,
				TimeUnit.MILLISECONDS);
				else writer.encodeVideo(0, bgrScreen, 60 * timeall,
				TimeUnit.MILLISECONDS);
			}


			// sleep for frame rate milliseconds

		}

		System.out.println("Created frames - 4");

		// tell the writer to close and write the movie if  needed
		writer.close();

		System.out.println("Video Created - 5 Works");
		warn.setText("Success");
		click = false;
		if (tmprmv.isSelected()) {
			deleteDirectory(new File("temp"));

			boolean success = (

			new File("temp")).mkdir();
			if (success) {
				System.out.println("Directory: temp created");
			}
		}


	}








	//************** CREATE GIF **************
	void creategif() {


		if (numofph > 1) {


			Image image = null;
			try {
				File f = new File("temp/screenshot" + 0 + ".jpg");
				File f2 = new File("temp/screenshot" + 1 + ".jpg");
				File f3 = new File("temp/screenshot" + 2 + ".jpg");
				File f4 = new File("temp/screenshot" + 3 + ".jpg");
				File f5 = new File("temp/screenshot" + 4 + ".jpg");
				if (f.exists() && !f.isDirectory()) {
					image = ImageIO.read(new File("temp/screenshot" + 0 + ".jpg"));
				} else if (f2.exists() && !f2.isDirectory()) {
					image = ImageIO.read(new File("temp/screenshot" + 1 + ".jpg"));
				} else if (f3.exists() && !f3.isDirectory()) {
					image = ImageIO.read(new File("temp/screenshot" + 2 + ".jpg"));
				} else if (f4.exists() && !f4.isDirectory()) {
					image = ImageIO.read(new File("temp/screenshot" + 3 + ".jpg"));
				} else if (f5.exists() && !f5.isDirectory()) {
					image = ImageIO.read(new File("temp/screenshot" + 4 + ".jpg"));
				} else {
					image = ImageIO.read(new File("temp/screenshot" + 5 + ".jpg"));
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				String message = "Gif not created... Failed to read first screenshot";
				JOptionPane.showMessageDialog(new JFrame(), message, "Error",
				JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			}

			BufferedImage firstImage = (BufferedImage) image;

			ImageOutputStream output = null;
			try {
				output = new FileImageOutputStream(new File("image" + UUID.randomUUID() + ".gif"));
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				String message = "Gif not created... Problem with output";
				JOptionPane.showMessageDialog(new JFrame(), message, "Error",
				JOptionPane.ERROR_MESSAGE);
				e1.printStackTrace();
			}


			GifSequenceWriter writer = null;
			try {
				if (fpss) writer = new GifSequenceWriter(output, firstImage.getType(), 40, true);
				else writer = new GifSequenceWriter(output, firstImage.getType(), 70, true);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				String message = "Gif not created... Gif writer initialize failure";
				JOptionPane.showMessageDialog(new JFrame(), message, "Error",
				JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			}



			for (int i = 0; i < numofph; i++) {

				File ft = new File("temp/screenshot" + i + ".jpg");
				if (ft.exists() && !ft.isDirectory()) {
					Image imager = null;
					try {
						imager = ImageIO.read(new File("temp/screenshot" + i + ".jpg"));

					} catch (IOException e) {
						// TODO Auto-generated catch block
						String message = "Gif not created...Problem with reading image";
						JOptionPane.showMessageDialog(new JFrame(), message, "Error",
						JOptionPane.ERROR_MESSAGE);
						e.printStackTrace();
					}

					BufferedImage nextImage = (BufferedImage) imager;
					try {
						if (nextImage != null) writer.writeToSequence(nextImage);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						String message = "Gif not created... writing problem";
						JOptionPane.showMessageDialog(new JFrame(), message, "Error",
						JOptionPane.ERROR_MESSAGE);
						e.printStackTrace();
					}
				}
			}




			try {
				writer.close();
				output.close();
				System.out.println("Perfect = GIF CREATED");
				warn.setText("Success");
				click = false;

				if (tmprmv.isSelected()) {
					deleteDirectory(new File("temp"));

					boolean success = (

					new File("temp")).mkdir();
					if (success) {
						System.out.println("Directory: temp created");
					}
				}

			} catch (IOException e) {
				// TODO Auto-generated catch block
				String message = "Gif not created... writer error";
				JOptionPane.showMessageDialog(new JFrame(), message, "Error",
				JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			}


		} else {
			System.out.println("GIF = only one image!");
			String message = "Gif not created... Only one image";
			JOptionPane.showMessageDialog(new JFrame(), message, "Error",
			JOptionPane.ERROR_MESSAGE);
		}

	}


	private AudioFormat getAudioFormat() {


		float sampleRate = 8000.0F;
		//8000,11025,16000,22050,44100
		int sampleSizeInBits = 16;
		//8,16
		int channels = 1;
		//1,2
		boolean signed = true;
		//true,false
		boolean bigEndian = false;
		//true,false

		return new AudioFormat(sampleRate,
		sampleSizeInBits,
		channels,
		signed,
		bigEndian);



	} //end getAudioFormat


	void captureaudio() {

		try {
			audioFormat = getAudioFormat();


			DataLine.Info dataLineInfo = new DataLine.Info(
			TargetDataLine.class,
			audioFormat);

			targetDataLine = (TargetDataLine)
			AudioSystem.getLine(dataLineInfo);

			new CaptureThread().start();
		} catch (Exception e) {
			String message = "Capture microphone problem";
			JOptionPane.showMessageDialog(new JFrame(), message, "Error",
			JOptionPane.ERROR_MESSAGE);
			e.printStackTrace();
		} //end catch
	} //end captureAudio method



	class CaptureThread extends Thread {
		public void run() {
			AudioFileFormat.Type fileType = null;
			File audioFile = null;



			fileType = AudioFileFormat.Type.WAVE;
			audioFile = new File("microphone.wav");

			try {
				targetDataLine.open(audioFormat);
				targetDataLine.start();
				AudioSystem.write(
				new AudioInputStream(targetDataLine),
				fileType,
				audioFile);
			} catch (Exception e) {
				String message = "Capture microphone thread problem";
				JOptionPane.showMessageDialog(new JFrame(), message, "Error",
				JOptionPane.ERROR_MESSAGE);
				e.printStackTrace();
			} //end catch

		} //end run
	}


	public static void main(String[] args) {

		Main main = new Main();
		main.setVisible(true);
	}
}