<commit_before>package gui;

import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.UIManager;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.KeyAdapter;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.swing.ImageIcon;
import java.awt.Image;
import javax.swing.JDialog;
import javax.swing.KeyStroke;
import javax.swing.border.EmptyBorder;

import snitt.SnittWindow;

import datastruct.CompareFile;
import datastruct.AlignmentManager;
import datastruct.Filter;
import datastruct.IOHandler;
import datastruct.NameList;
import datastruct.ResultList;
import datastruct.DataStore;

import java.util.StringTokenizer;

/** klassen som beskriver sjlva huvudfnstret och delen fr skning */
public class SearchWindow {
	private HashMap personTracker;			// hller reda p vem personen r ven om ngon persondata ndras
	private HashMap personNameTracker;		// lagrar namnet som idnumret tillhr
	private NameList name;					// namnlista som anvnds fr skning
	private ResultInputWindow resultInput;	// fnstret fr indata
	private JFrame frame;					// huvudfnster
	private JPanel searchPanel;				// panelen fr skfltet
	private LapSumDialog lapSumDialog; 		// redigeringsfnstret
	private JDialog compInfoDialog;			// indatafnster
	private JTextField searchField,nameField,clubField;	// skflt, namn- och klubbflt fr namnlistan
	public static JTextField STATUSFIELD,MESSAGEFIELD;	// meddelande- och statusflt
	private JButton[] button;							// knapparna med funna personer som matchar skningen
	private JButton addPlayerButton,removePlayerButton;	// lgg till och ta bort spelare
	private JMenuItem newComp, openFromSKV, save;		// meny fr ny tvling och ppna samt spara
	private	JMenuItem saveToHTML, quit, editItem; 		// spara till HTML, avsluta, redigera
	private JMenuItem klassStart, snittStart, about;	// hantera klasser och snittlista, om programmet
	private JMenuItem setLookAndFeel;					// stll in programmets look and feel 
	private JMenuItem makeCompareFile, openCompareFile;	// skapar eller ppnar en jmfrande snittlista
	private JMenuItem headerItem, saveAs, saveAsHTML;	// stter tvlingens namn, spara som fr SKV- och HTML-filer
	private JMenuItem changeName, changeClub;			// ndra namn och klubb p en spelare
	private JMenuItem numberOrientation;				// alternativ fr sifferorienteringen
	private JLabel inputNameLabel;				// innehller namnet p den person som resultat skrivs in fr
	private JFileChooser fileChooser;			// filvljare
	private Filter skvFilter, htmFilter;		// filter fr skv- och htmfiler
	private Filter snittFilter;					// filter fr snittfiler
	private IOHandler io;						// skter skrivning till och lsning frn filer
	private AlignmentManager alignmentManager;	// hller reda p instllningarna fr sifferorientering
	public static boolean SNITTOPEN, KLASSOPEN;	// talar om ifall motsvarande fnster r ppet
	private boolean warningHTM;					// varnar fr att inte skriva till ej nskvrd fil
	private boolean compInfoDialogClosed;		// talar om ifall indatafnstret har stngts ner utan anvndande av knappen Ok
	public static boolean CHANGE;				// hller reda p om ndringar har skett som br sparas
	public static Image ICON;					// programmets ikon
	private KlassWindow klassWindow;			// klasshanterarfnstret
	private SnittWindow snittWindow;			// snittlistshanterarfnstret
	private String compHeader, fileNameSKV, fileNameHTM;// tvlingsrubrik, filnamn fr SKV- och HTML-filerna
	private String fileNameSNITT;				// filnamn fr SNITT-fil
	public static File DIRSKV, DIRHTM, DIRSNITT, DIRJMF;// mappar fr olika filtyper
	public static final int DUMMY_STARTUP = 0;	// antal varv som anges vid "dum"-starten
	private int mode;							// talar om vilket lger som gller
	public static final int MODE_DUMMY = 0;		// heltal fr "dum"-lget
	public static final int MODE_COMP = 1;		// heltal fr lget dr vanlig tvling matas in
	public static final int MODE_SNITT = 2;		// heltal fr lget d man skapar en jmfrande snittlista
	
	/** skapar huvudfnstret */
	public SearchWindow() {
		name = new NameList();
		try {
			name.readNames();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Inlsningen av namnlistan misslyckades", "Varning", JOptionPane.ERROR_MESSAGE);
			name.sortedNames();
		}
		try {
			frame = new JFrame("BangolfResultat");
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Programmet gick ej att starta", "Programfel", JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		}
		try {
			ImageIcon frameIcon = new ImageIcon("data/brikon.gif");
			ICON = frameIcon.getImage();
			frame.setIconImage(ICON);
		} catch (Exception e) {
		}
		compHeader = "";
		fileNameSKV = null;
		fileNameHTM = null;
		warningHTM = false;
		CHANGE = false;
		
		alignmentManager = new AlignmentManager();
		if(!alignmentManager.loadOrientation()) {
		    JOptionPane.showMessageDialog(null, "Tidigare sifferorienteringsinstllningar gick ej att lsa in",
                    "Varning", JOptionPane.ERROR_MESSAGE);
		}
		
		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		WindowHandler window = new WindowHandler();
		frame.addWindowListener(window);
		
		searchPanel = new JPanel();
		searchPanel.setBorder(new EmptyBorder(5,5,5,5));
		button = new JButton[10];
		
		JLabel[] searchLabel = new JLabel[6];
		searchLabel[0] = new JLabel("Registrera, ndra eller ta bort resultat");
		searchLabel[1] = new JLabel("genom att ska upp spelaren i detta flt");
		searchLabel[2] = new JLabel("och sedan klicka p knappen med namnet:");
		searchLabel[3] = new JLabel("ndra i det skbara namnregistret:");
		searchLabel[4] = new JLabel("Namn:");
		searchLabel[5] = new JLabel("Klubb:");
		for(int i = 0; i < 4; i++) {
			searchLabel[i].setPreferredSize(new Dimension(250,15));
		}
		searchLabel[4].setPreferredSize(new Dimension(120,15));
		searchLabel[5].setPreferredSize(new Dimension(120,15));
		
		KeyHandler keyhand = new KeyHandler();
		searchField = new JTextField();
		searchField.setPreferredSize(new Dimension(240,20));
		searchField.addKeyListener(keyhand);
		
		nameField = new JTextField();
		nameField.setPreferredSize(new Dimension(120,20));
		clubField = new JTextField();
		clubField.setPreferredSize(new Dimension(120,20));
		GridBagLayout gridbag = new GridBagLayout();
		GridBagConstraints c = new GridBagConstraints();
		searchPanel.setLayout(gridbag);
		c.fill = GridBagConstraints.BOTH;
		c.insets = new Insets(0,1,0,1);
		c.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints(searchLabel[0], c);
		gridbag.setConstraints(searchLabel[1], c);
		gridbag.setConstraints(searchLabel[2], c);
		c.insets = new Insets(1,1,1,1);
		gridbag.setConstraints(searchField, c);
		gridbag.setConstraints(searchLabel[3], c);
		searchPanel.add(searchLabel[0]);
		searchPanel.add(searchLabel[1]);
		searchPanel.add(searchLabel[2]);
		searchPanel.add(searchField);
		
		SearchHandler searchHand = new SearchHandler();
		ButtonKeyHandler buttonHand = new ButtonKeyHandler();
		int key = KeyEvent.VK_0;
		for(int i = 0; i < 10; i++) {
			button[i] = new JButton();
			button[i].setMnemonic(key);
			key++;
			button[i].setPreferredSize(new Dimension(240,25));
			button[i].setHorizontalAlignment(SwingConstants.LEFT);
			button[i].setFocusable(false);
			button[i].addActionListener(searchHand);
			button[i].addKeyListener(buttonHand);
			gridbag.setConstraints(button[i], c);
			searchPanel.add(button[i]);
		}
		JLabel emptyLabel = new JLabel(" ");
		gridbag.setConstraints(emptyLabel, c);
		searchPanel.add(emptyLabel);
		c.gridwidth = 1;
		c.insets = new Insets(1,1,1,2);
		gridbag.setConstraints(searchLabel[4], c);
		c.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints(searchLabel[5], c);
		c.gridwidth = 1;
		gridbag.setConstraints(nameField, c);
		c.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints(clubField, c);
		c.gridwidth = 1;
		addPlayerButton = new JButton("Lgg till");
		addPlayerButton.setMnemonic(KeyEvent.VK_L);
		addPlayerButton.setPreferredSize(new Dimension(120,25));
		removePlayerButton = new JButton("Ta bort");
		removePlayerButton.setMnemonic(KeyEvent.VK_T);
		removePlayerButton.setPreferredSize(new Dimension(120,25));
		PlayerHandler playHand = new PlayerHandler();
		addPlayerButton.addActionListener(playHand);
		addPlayerButton.addKeyListener(buttonHand);
		removePlayerButton.addActionListener(playHand);
		removePlayerButton.addKeyListener(buttonHand);
		gridbag.setConstraints(addPlayerButton, c);
		c.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints(removePlayerButton, c);
		searchPanel.add(searchLabel[3]);
		searchPanel.add(searchLabel[4]);
		searchPanel.add(searchLabel[5]);
		searchPanel.add(nameField);
		searchPanel.add(clubField);
		searchPanel.add(addPlayerButton);
		searchPanel.add(removePlayerButton);
		
		JMenuBar bar = new JMenuBar();
		JMenu menu = new JMenu("Arkiv");
		menu.setMnemonic(KeyEvent.VK_A);
		JMenu edit = new JMenu("Redigera");
		edit.setMnemonic(KeyEvent.VK_R);
		JMenu klassMenu = new JMenu("Klasser");
		klassMenu.setMnemonic(KeyEvent.VK_K);
		JMenu snittMenu = new JMenu("Snittlistor");
		snittMenu.setMnemonic(KeyEvent.VK_S);
		JMenu windowMenu = new JMenu("Fnster");
		windowMenu.setMnemonic(KeyEvent.VK_F);
		JMenu help = new JMenu("Info");
		help.setMnemonic(KeyEvent.VK_I);
		bar.add(menu);
		bar.add(edit);
		bar.add(klassMenu);
		bar.add(snittMenu);
		bar.add(windowMenu);
		bar.add(help);
		MenuHandler menuHand = new MenuHandler();
		newComp = new JMenuItem("Ny tvling...", KeyEvent.VK_N);
		newComp.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
		openFromSKV = new JMenuItem("ppna tvling...", KeyEvent.VK_P);
		openFromSKV.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
		save = new JMenuItem("Spara", KeyEvent.VK_S);
		save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
		save.setEnabled(false);
		saveAs = new JMenuItem("Spara som...", KeyEvent.VK_M);
		saveAs.setEnabled(false);
		saveToHTML = new JMenuItem("Skapa webbsida", KeyEvent.VK_W);
		saveToHTML.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
		saveToHTML.setEnabled(false);
		saveAsHTML = new JMenuItem("Skapa webbsida som...", KeyEvent.VK_B);
		saveAsHTML.setEnabled(false);
		quit = new JMenuItem("Avsluta", KeyEvent.VK_A);
		headerItem = new JMenuItem("Ange tvlingens rubrik...", KeyEvent.VK_R);
		headerItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK));
		headerItem.setEnabled(false);
		editItem = new JMenuItem("Delsummor och placering...", KeyEvent.VK_D);
		editItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK));
		editItem.setEnabled(false);
		numberOrientation = new JMenuItem("Sifferorientering...", KeyEvent.VK_O);
		numberOrientation.setEnabled(false);
		klassStart = new JMenuItem("Hantera klasser...", KeyEvent.VK_H);
		klassStart.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ActionEvent.CTRL_MASK));
		snittStart = new JMenuItem("Hantera snittlistor...", KeyEvent.VK_H);
		snittStart.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
		makeCompareFile = new JMenuItem("Ny jmfrande snittlista...", KeyEvent.VK_N);
		openCompareFile = new JMenuItem("ppna jmfrande snittlista...", KeyEvent.VK_P);
		setLookAndFeel = new JMenuItem("Vlj utseende och knsla...", KeyEvent.VK_U);
		about = new JMenuItem("Om BangolfResultat...", KeyEvent.VK_O);
		newComp.addActionListener(menuHand);
		saveToHTML.addActionListener(menuHand);
		saveAsHTML.addActionListener(menuHand);
		saveAs.addActionListener(menuHand);
		save.addActionListener(menuHand);
		openFromSKV.addActionListener(menuHand);
		quit.addActionListener(menuHand);
		headerItem.addActionListener(menuHand);
		editItem.addActionListener(menuHand);
		numberOrientation.addActionListener(menuHand);
		klassStart.addActionListener(menuHand);
		snittStart.addActionListener(menuHand);
		makeCompareFile.addActionListener(menuHand);
		openCompareFile.addActionListener(menuHand);
		setLookAndFeel.addActionListener(menuHand);
		about.addActionListener(menuHand);
		menu.add(newComp);
		menu.add(openFromSKV);
		menu.addSeparator();
		menu.add(save);
		menu.add(saveAs);
		menu.add(saveToHTML);
		menu.add(saveAsHTML);
		menu.addSeparator();
		menu.add(quit);
		edit.add(headerItem);
		edit.addSeparator();
		edit.add(editItem);
		edit.add(numberOrientation);
		klassMenu.add(klassStart);
		snittMenu.add(snittStart);
		snittMenu.addSeparator();
		snittMenu.add(makeCompareFile);
		snittMenu.add(openCompareFile);
		windowMenu.add(setLookAndFeel);
		help.add(about);
		frame.setJMenuBar(bar);
		
		JMenuBar resBar = new JMenuBar();
		JMenu resMenu = new JMenu("Redigera");
		resMenu.setMnemonic(KeyEvent.VK_R);
		resBar.add(resMenu);
		changeName = new JMenuItem("ndra namn...", KeyEvent.VK_N);
		changeName.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
		changeClub = new JMenuItem("ndra klubb...", KeyEvent.VK_K);
		changeClub.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ActionEvent.CTRL_MASK));
		changeName.addActionListener(menuHand);
		changeClub.addActionListener(menuHand);
		resMenu.add(changeName);
		resMenu.add(changeClub);
		
		io = new IOHandler();
		try {
			personTracker = (HashMap) io.load("ptrack");
		} catch (Exception e) {
			personTracker = new HashMap();
			personTracker.put(" ", new Integer(0));
		}
		try {
			personNameTracker = (HashMap) io.load("pnametrack");
		} catch (Exception e) {
			personNameTracker = new HashMap();
		}
		
		JPanel statusPanel = new JPanel();
		statusPanel.setLayout(new BorderLayout());
		MESSAGEFIELD = new JTextField("Starta ny tvling genom att klicka p Arkiv -> Ny tvling...");
		MESSAGEFIELD.setEditable(false);
		MESSAGEFIELD.setFocusable(false);
		STATUSFIELD = new JTextField();
		STATUSFIELD.setEditable(false);
		STATUSFIELD.setHorizontalAlignment(JTextField.CENTER);
		STATUSFIELD.setPreferredSize(new Dimension(20,10));
		STATUSFIELD.setFocusable(false);
		statusPanel.add(MESSAGEFIELD, BorderLayout.CENTER);
		statusPanel.add(STATUSFIELD, BorderLayout.WEST);
		resultInput = new ResultInputWindow(frame, resBar, personTracker, personNameTracker);
		lapSumDialog = new LapSumDialog(frame);
		compInfoDialog = new CompInfoDialog(frame, this);
		compInfoDialog.addWindowListener(new WinHandForCompInfoDialog());
		
		fileChooser = new JFileChooser();
		skvFilter = new Filter(new String[]{"skv"}, "Semikolonseparerad fil");
		htmFilter = new Filter(new String[]{"htm", "html"}, "Webbsida");
		snittFilter = new Filter(new String[]{"snitt"}, "Jmfrelsefil fr snittlista");
		try {
			DIRSKV = (File) io.load("dirskv");
			DIRHTM = (File) io.load("dirhtm");
			DIRSNITT = (File) io.load("dirsnitt");
			DIRJMF = (File) io.load("dirjmf");
		} catch (Exception e) {
			DIRSKV = null;
			DIRHTM = null;
			DIRSNITT = null;
			DIRJMF = null;
		}
		
		frame.getContentPane().add(searchPanel, BorderLayout.WEST);
		frame.getContentPane().add(statusPanel, BorderLayout.SOUTH);
		dummyStartUp();
		frame.pack();
		frame.setVisible(true);
	}
	
	/** fixar till menyalternativen fr skapandet av en jmfrelsesnittlista */
	private void enableCompareFileMenus() {
	    headerItem.setEnabled(false);
		editItem.setEnabled(false);
		numberOrientation.setEnabled(false);
	    save.setEnabled(true);
		saveAs.setEnabled(true);
		saveToHTML.setEnabled(false);
		saveAsHTML.setEnabled(false);
	}
	
	/** gr menyalternativen under Redigera och de olika alternativen fr att spara tillgngliga */
	private void enableDisabledMenus() {
	    headerItem.setEnabled(true);
		editItem.setEnabled(true);
		numberOrientation.setEnabled(true);
	    save.setEnabled(true);
		saveAs.setEnabled(true);
		saveToHTML.setEnabled(true);
		saveAsHTML.setEnabled(true);
		setMode(SearchWindow.MODE_COMP, null);
	}
	
	/** stller lget till mode, alternativen r MODE_COMP, MODE_DUMMY och MODE_SNITT 
	 * 	skickar med ett objekt o som anvnds vid vissa tillfllen */
	private void setMode(int mode, Object o) {
	    int oldMode = this.mode;
	    this.mode = mode;
	    if(mode == SearchWindow.MODE_SNITT) {
	        CompareFile compareFile = (CompareFile) o;
	        if(compareFile == null) {
	            compareFile = new CompareFile(newCompareFile());
	        }
	        if(compareFile.getSurface() != -1) {
	            resultInput.setCompareFile(compareFile);
	            resultInput.setupResultInputPanel(mode);
	        } else {
	            this.mode = oldMode;
	        }
	    }
	}
	
	/** startar upp saker fr att skapa en jmfrelsesnittlista */
	private int newCompareFile() {
	    int surface = -1;
	    int val = JOptionPane.YES_OPTION;
		if(CHANGE) {
			val = JOptionPane.showConfirmDialog(frame, "De senaste ndringarna r ej sparade. Vill du spara nu?"
			, "Spara?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
			if(val == JOptionPane.YES_OPTION) {
				autoSave();
			}
		}
		if(!CHANGE || val == JOptionPane.NO_OPTION) {
		    String[] possibleValues = { "Filt", "EB", "Betong", "Blandad" };
		    String selectedValue = (String) JOptionPane.showInputDialog(frame, "Vlj underlag", "Indata", 
		            JOptionPane.INFORMATION_MESSAGE, null, possibleValues, possibleValues[0]);
			if(selectedValue != null) {
	            if(selectedValue.equals(possibleValues[0])) {
	                surface = ResultList.FILT;
	            } else if(selectedValue.equals(possibleValues[1])) {
	                surface = ResultList.EB;
	            } else if(selectedValue.equals(possibleValues[2])) {
	                surface = ResultList.BETONG;
	            } else if(selectedValue.equals(possibleValues[3])) {
	                surface = SnittWindow.BLANDAD;
	            }
				compHeader = "";
				fileNameSKV = null;
				fileNameHTM = null;
				fileNameSNITT = null;
				warningHTM = false;
				CHANGE = false;
				STATUSFIELD.setText("");
				MESSAGEFIELD.setText("Ny jmfrelsesnittlista har ppnats.");
				ScoreBoardWindow.setHeader(compHeader);
				inputNameLabel = resultInput.getNameLabel();
				enableCompareFileMenus();
			}
		}
		return surface;
	}
	
	/** ppnar en ny tvling bara fr att f igng programmet korrekt */
	private void dummyStartUp() {
	    setMode(SearchWindow.MODE_DUMMY, null);
	    ResultInputWindow.RESULTLIST = new ResultList(2, 0, new boolean[]{false, false});
		ResultInputWindow.BOARD = new ScoreBoardWindow(ResultInputWindow.RESULTLIST);
		frame.getContentPane().add(ResultInputWindow.BOARD.getScrollPane(), BorderLayout.CENTER);
		resultInput.setupResultInputPanel(MODE_DUMMY);
		inputNameLabel = resultInput.getNameLabel();
	}
	
	/** stller in resultatinmatningsfnstret och fnstret fr delsummor, init r true om 
	 *  ingen ny resultatlista behver skapas, boxData[0] talar om ifall startnummer skall vara med,
	 *  boxData[1] sger om licensnummer skall vara med, nbrRounds r antal varv och surface anger
	 *  tvlingens underlag */
	protected void setupResultInputPanel(boolean init, boolean[] boxData, int nbrRounds, int surface) {
	    resultInput.setupResultInputPanel(init, boxData, nbrRounds, surface);
	    lapSumDialog.setNbrRounds(nbrRounds);
	    lapSumDialog.setEditData(new boolean[nbrRounds-1]);
	}
	
	/** uppdaterar skresultaten */
	private void updatePersonMatch() {
		String search = searchField.getText();
		String[] names = name.getNames(search);
		for(int i = 0; i < 10; i++) {
			if(names[i] != null) {
				button[i].setFocusable(true);
				button[i].setText(i + ". " + names[i]);
			}
			else {
				button[i].setFocusable(false);
				button[i].setText("");
			}
		}
	}
	
	/** skter om avslutandet av programmet */
	private void exit() {
		int val = JOptionPane.YES_OPTION;
		if(CHANGE) {
			val = JOptionPane.showConfirmDialog(frame, "De senaste ndringarna r ej sparade. Vill du spara nu?"
			, "Spara?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
			if(val == JOptionPane.YES_OPTION) {
				autoSave();
			}
		}
		if(!CHANGE || val == JOptionPane.NO_OPTION) {
			if(SNITTOPEN) {
				snittWindow.exit();
			}
			if(KLASSOPEN) {
				klassWindow.exit();
			}
			save();
			System.exit(0);
		}
	}
	
	/** sparar filer som programmet anvnder sig av */
	private void save() {
	    if(!alignmentManager.saveOrientation()) {
	        JOptionPane.showMessageDialog(frame, "Orienteringsinstllningarna gick ej att spara",
                    "Varning", JOptionPane.ERROR_MESSAGE);
	    }
		try {
			io.save("licensemap", resultInput.getLicenseMap());
			io.save("licensenamemap", resultInput.getLicenseIDMap());
		} catch (Exception e) {
			JOptionPane.showMessageDialog(frame, "Listan ver licensnummer gick ej att spara", "Varning", JOptionPane.ERROR_MESSAGE);
		}
		try {
			name.writeNames();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(frame, "Namnlistan gick ej att spara", "Varning", JOptionPane.ERROR_MESSAGE);
		}
		try {
			io.save("dirskv", DIRSKV);
			io.save("dirhtm", DIRHTM);
			io.save("dirsnitt", DIRSNITT);
			io.save("dirjmf", DIRJMF);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(frame, "Senast anvnda mappar gick ej att spara", "Varning", JOptionPane.ERROR_MESSAGE);
		}
		try {
			io.save("ptrack", personTracker);
			io.save("pnametrack", personNameTracker);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(frame, "Intern ID-lista gick ej att spara", "Varning", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	/** sparar efter uppmaning */
	private void autoSave() {
		MenuHandler menu = new MenuHandler();
		if(mode == MODE_COMP) {
		    menu.saveToSKV();
		} else if(mode == MODE_SNITT) {
		    menu.saveToSNITT();
		}
	}
	
	/** talar om fr resultatinmatningsfnstret vilken person som valts */
	private void setPopup(JButton b) {
	    searchField.selectAll();
		searchField.requestFocus();
		resultInput.setPopup(b, mode);
	}

    /** lgger till och tar bort personen frn namnlistan, lgger till om add r true */
	private void handlePlayer(boolean add) {
		boolean done = false;
		boolean visit = false;
		int confirmValue =  JOptionPane.NO_OPTION;
		String nameString = nameField.getText().trim();
		String clubString = clubField.getText().trim();
		if(!nameString.equals("") && !clubString.equals("")) {
			if(add) {
				done = name.add(nameString, clubString);
				if(done) {
					addPerson(nameString + ", " + clubString);
				}
				name.sortedNames();
				visit = true;
			} else {
			    if(name.containsPerson(nameString, clubString)) {
			        confirmValue = JOptionPane.showConfirmDialog(frame, "r du sker p att du vill ta bort "
			                + nameString + ", " + clubString + ", permanent?");
			        if(confirmValue == JOptionPane.YES_OPTION) {
			            done = name.remove(nameString, clubString);
			            if(done) {
			                resultInput.removeFromLicenseMap((Integer) personTracker.get(nameString + 
			                        ", " + clubString));
			            }
			            name.sortedNames();
			            visit = true;
			        } else if (confirmValue == JOptionPane.NO_OPTION) {
			            nameField.setText("");
			            clubField.setText("");
			        }
			    } else {
			        visit = true;
			    }
			}
		} else {
			JOptionPane.showMessageDialog(frame, "Flten mste innehlla mer n blanksteg!");
		}
		if(done && visit) {
			if(!add) {
				updatePersonMatch();
				save();
				MESSAGEFIELD.setText(nameString + ", " + clubString + ", r nu borttagen frn skningsfltet.");
			} else {
				updatePersonMatch();
				save();
				MESSAGEFIELD.setText(nameString + ", " + clubString + ", har nu lagts till i skningsfltet.");
			}
			nameField.setText("");
			clubField.setText("");
		} else if(visit) {
		    if(!add) {
		        JOptionPane.showMessageDialog(frame, nameString + ", " + clubString + 
		        ", gick inte att ta bort frn skningsfltet. Kolla s att rtt namn och klubb r angiven.");		        
		    } else {
		        JOptionPane.showMessageDialog(frame, nameString + ", " + clubString + 
		        ", gick inte att lgga till i skningsfltet. Kolla s att personen inte redan finns dr.");
		    }
		}
	}
	
	/** lgger till personen identity i listan ver idnummer */
	private void addPerson(String identity) {
		Integer i = (Integer) personTracker.get(" ");
		personTracker.put(identity, i);
		personNameTracker.put(i, identity);
		personTracker.put(" ", new Integer(i.intValue() + 1));
	}
	
	/** loggar informationen om Throwable throwable */
	private static void logError(Throwable throwable) {
	    JOptionPane.showMessageDialog(null, "Ett fel i programmet har uppsttt. " +
        		"Informationen om detta sparas i filen error.log.\n" +
        		"Denna fil finns i katalogen dr programmet installerades, " +
        		"vanligtvis C:\\Program\\BangolfResultat.\n\n" +
        		"Var vnlig spara aktivt arbete och starta om programmet.\n" +
        		"Om problem uppstr igen tag kontakt med programmets tillverkare.",
        		"Varningsmeddelande", JOptionPane.WARNING_MESSAGE);
	    if(IOHandler.logError(throwable)) {
	        JOptionPane.showMessageDialog(null, "Loggningen r klar.");
	    } else {
	        JOptionPane.showMessageDialog(null, "Loggningen misslyckades.");
	    }
	}
	
	/** mainmetoden som startar hela programmet */
	public static void main(String[] args) {
	    System.setProperty("sun.awt.exception.handler", "gui.SearchWindow$ErrorHandler");
	    
	    Object lookAndFeel = DataStore.get(DataStore.LOOK_AND_FEEL);
	    try {
	    	if (lookAndFeel != null) {
	    		UIManager.setLookAndFeel((String) lookAndFeel);
	    	}
	    } catch (Exception e) {
	    	//e.printStackTrace();
	    }
	    
	    new SearchWindow();
	}

    /** klassen som tar hand om knapptryckningarna i menyn */
    class MenuHandler implements ActionListener {
    	/** kollar vilket menyalternativ som valts och utfr lmplig handling */
    	public void actionPerformed(ActionEvent e) {
    		if(e.getSource() == saveToHTML) {
    			if(fileNameHTM == null) {
    				saveAsHTML();
    			} else {
    				try {
    					boolean doit = true;
    					if(warningHTM) {
    						int val = JOptionPane.showConfirmDialog(frame, "Vill du att webbsidan sparas till filen " + fileNameHTM + "?"
    						, "Spara webbsida", JOptionPane.YES_NO_OPTION);
    						if(val != JOptionPane.YES_OPTION) {
    							doit = false;
    						}
    					}
    					if(doit) {
    					    int align = AlignmentManager.getOrientation(AlignmentWindow.COMP_OWNER);
    						io.outputToHTML(fileNameHTM, resultInput.getResultList(), compHeader, align);
    						warningHTM = false;
    						MESSAGEFIELD.setText("Tvlingen r sparad som webbsida.");
    					} else {
    						saveAsHTML();
    					}
    				} catch (Exception f) {
    					JOptionPane.showMessageDialog(frame, "Skrivning till HTML-fil misslyckades", "Varning", JOptionPane.ERROR_MESSAGE);
    				}
    			}
    		}
    		else if(e.getSource() == saveAsHTML) {
    			saveAsHTML();
    		}
    		else if(e.getSource() == save) {
    		    if(mode == MODE_COMP) {
    		        saveToSKV();
    		    } else if(mode == MODE_SNITT) {
    		        saveToSNITT();
    		    }
    		}
    		else if(e.getSource() == saveAs) {
    		    if(mode == MODE_COMP) {
    		        saveAsSKV();
    		    } else if(mode == MODE_SNITT) {
    		        saveAsSNITT();
    		    }
    		}
    		else if(e.getSource() == openFromSKV) {
    			int val = JOptionPane.YES_OPTION;
    			if(CHANGE) {
    				val = JOptionPane.showConfirmDialog(frame, "De senaste ndringarna r ej sparade. Vill du spara nu?"
    				, "Spara?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    				if(val == JOptionPane.YES_OPTION) {
    					autoSave();
    				}
    			}
    			if(!CHANGE || val == JOptionPane.NO_OPTION) {
    				fileChooser.setCurrentDirectory(DIRSKV);
    				fileChooser.setSelectedFile(new File(""));
    				fileChooser.setFileFilter(skvFilter);
    				int retval = fileChooser.showOpenDialog(frame);
    				if(retval == JFileChooser.APPROVE_OPTION) {
    					File file = fileChooser.getSelectedFile();
    					DIRSKV = fileChooser.getCurrentDirectory();
    					fileNameSKV = file.getPath();
    					if(!fileNameSKV.endsWith(".skv")) {
    						fileNameSKV = fileNameSKV + ".skv";
    					}
    					if(new File(fileNameSKV).exists()) {
    					    try {
    					        Object[] o = io.inputFromSKV(fileNameSKV);
    					        compHeader = (String)o[0];
    					        fileNameHTM = (String)o[1];
    					        warningHTM = true;
    					        ResultList result = (ResultList) o[2];
    					        resultInput.init(result);
    					        resultInput.setStartNbrMap((HashMap)o[3]);
    					        lapSumDialog.setNbrRounds(result.getNbrRounds());
    					        lapSumDialog.setEditData((boolean[])o[4]);
    					        ScoreBoardWindow.setHeader(compHeader);
    					        inputNameLabel = resultInput.getNameLabel();
    					        CHANGE = false;
    					        STATUSFIELD.setText("");
    					        MESSAGEFIELD.setText("ppnat filen: " + fileNameSKV + ".");
    					        enableDisabledMenus();
    					    } catch (Exception f) {
    					        JOptionPane.showMessageDialog(frame, "Inlsningen frn SKV-fil misslyckades", "Varning", JOptionPane.ERROR_MESSAGE);
    					    }
    					} else {
    					    JOptionPane.showMessageDialog(frame, "Filen, " + fileNameSKV + ", existerar inte", "Varning", JOptionPane.ERROR_MESSAGE);
    					}
    				}
    			}
    		}
    		else if(e.getSource() == newComp) {
    			int val = JOptionPane.YES_OPTION;
    			if(CHANGE) {
    				val = JOptionPane.showConfirmDialog(frame, "De senaste ndringarna r ej sparade. Vill du spara nu?"
    				, "Spara?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    				if(val == JOptionPane.YES_OPTION) {
    					autoSave();
    				}
    			}
    			if(!CHANGE || val == JOptionPane.NO_OPTION) {
    				compInfoDialog.setLocationRelativeTo(frame);
    				compInfoDialog.setVisible(true);
    				if(!compInfoDialogClosed) {
    					compHeader = "";
    					fileNameSKV = null;
    					fileNameHTM = null;
    					warningHTM = false;
    					CHANGE = false;
    					STATUSFIELD.setText("");
    					MESSAGEFIELD.setText("Ny tvling har ppnats.");
    					ScoreBoardWindow.setHeader(compHeader);
    					inputNameLabel = resultInput.getNameLabel();
    					enableDisabledMenus();
    				} else {
    					compInfoDialogClosed = false;
    				}
    			}
    		}
    		else if(e.getSource() == editItem) {
    			lapSumDialog.setEditWindow();
    			lapSumDialog.getContentPane().add(lapSumDialog.lapSumPanel(), BorderLayout.NORTH);
    			lapSumDialog.pack();
    			lapSumDialog.setLocationRelativeTo(frame);
    			lapSumDialog.setVisible(true);
    		}
    		else if(e.getSource() == headerItem) {
    			String tempHeader = JOptionPane.showInputDialog(frame, "Skriv in rubriken fr tvlingen", ScoreBoardWindow.getHeader());
    			if(tempHeader != null) {
    				compHeader = tempHeader;
    				ScoreBoardWindow.setHeader(compHeader);
    				CHANGE = true;
    				STATUSFIELD.setText("*");
    				MESSAGEFIELD.setText("");
    			}
    		}
    		else if(e.getSource() == numberOrientation) {
    		    new AlignmentWindow(frame, AlignmentWindow.COMP_OWNER, alignmentManager);
    		}
    		else if(e.getSource() == klassStart) {
    			if(!KLASSOPEN) {
    				KLASSOPEN = true;
    				klassWindow = new KlassWindow(frame);
    			} else {
    				klassWindow.setVisible(true);
    			}
    		}
    		else if(e.getSource() == snittStart) {
    			if(!SNITTOPEN) {
    				SNITTOPEN = true;
    				snittWindow = new SnittWindow(frame, personNameTracker, alignmentManager);
    			} else {
    				snittWindow.setVisible(true);
    			}
    		}
    		/** ppnar fnster fr att mata in en jmfrelsesnittlista */
			else if(e.getSource() == makeCompareFile) {
			    setMode(SearchWindow.MODE_SNITT, null);
			}
			else if(e.getSource() == openCompareFile) {
    			int val = JOptionPane.YES_OPTION;
    			if(CHANGE) {
    				val = JOptionPane.showConfirmDialog(frame, "De senaste ndringarna r ej sparade. Vill du spara nu?"
    				, "Spara?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    				if(val == JOptionPane.YES_OPTION) {
    					autoSave();
    				}
    			}
    			if(!CHANGE || val == JOptionPane.NO_OPTION) {
    				fileChooser.setCurrentDirectory(DIRJMF);
    				fileChooser.setSelectedFile(new File(""));
    				fileChooser.setFileFilter(snittFilter);
    				int retval = fileChooser.showOpenDialog(frame);
    				if(retval == JFileChooser.APPROVE_OPTION) {
    					File file = fileChooser.getSelectedFile();
    					DIRJMF = fileChooser.getCurrentDirectory();
    					fileNameSNITT = file.getPath();
    					if(!fileNameSNITT.endsWith(".snitt")) {
    						fileNameSNITT = fileNameSNITT + ".snitt";
    					}
    					if(new File(fileNameSNITT).exists()) {
    					    try {
    					        CompareFile compareFile = io.inputFromSNITT(fileNameSNITT);
    					        setMode(MODE_SNITT, compareFile);
    					        CHANGE = false;
    					        STATUSFIELD.setText("");
    					        MESSAGEFIELD.setText("ppnat filen: " + fileNameSNITT + ".");
    					        enableCompareFileMenus();
    					    } catch (IOException ioe) {
    					        JOptionPane.showMessageDialog(frame, "Inlsningen frn SNITT-fil misslyckades", "Varning", JOptionPane.ERROR_MESSAGE);
    					    }
    					} else {
    					    JOptionPane.showMessageDialog(frame, "Filen, " + fileNameSNITT + ", existerar inte", "Varning", JOptionPane.ERROR_MESSAGE);
    					}
    				}
    			}
	    	}
			else if(e.getSource() == setLookAndFeel) {
				String java = "Java";
				String system = "Naturlig";
				String initialSelectionValue = java;
				Object lookAndFeel = DataStore.get(DataStore.LOOK_AND_FEEL);
				if (lookAndFeel != null) {
					if (((String) lookAndFeel).equals(
							UIManager.getSystemLookAndFeelClassName())) {
						initialSelectionValue = system;
					}
				}
				String newLookAndFeel = (String) JOptionPane.showInputDialog(
						frame, "Vlj utseende och knsla:\n(Brjar glla nr BangolfResultat har startats om.)",
						"Utseende och knsla", JOptionPane.INFORMATION_MESSAGE,
						null, new String[]{java,system}, initialSelectionValue);
				if (newLookAndFeel != null) {
					if (newLookAndFeel.equals(java)) {
						DataStore.set(DataStore.LOOK_AND_FEEL, UIManager.getCrossPlatformLookAndFeelClassName());
					} else if (newLookAndFeel.equals(system)) {
						DataStore.set(DataStore.LOOK_AND_FEEL, UIManager.getSystemLookAndFeelClassName());
					}
				}
			}
    		else if(e.getSource() == about) {
    			new AboutWindow(frame);
    		}
    		else if(e.getSource() == quit) {
    			exit();
    		}
    		else if(e.getSource() == changeName) {
    			StringTokenizer inString = new StringTokenizer(inputNameLabel.getText(), ",");
    			String labelName = inString.nextToken();
    			String labelClub = inString.nextToken().trim();
    			String newName = JOptionPane.showInputDialog(frame, "Skriv in nytt namn", labelName);
    			if(newName != null && newName.trim() != "") {
    				if(name.add(newName, labelClub)) {
    					name.remove(labelName, labelClub);
    					name.sortedNames();
    					updatePersonMatch();
    					Integer personID = (Integer) personTracker.get(labelName + ", " + labelClub);
    					personTracker.remove(labelName + ", " + labelClub);
    					personTracker.put(newName + ", " + labelClub, personID);
    					personNameTracker.put(personID, newName + ", " + labelClub);
    					inputNameLabel.setText(newName + ", " + labelClub);
    					resultInput.updateNameAndClub(labelName, labelClub, newName, labelClub, personID);
    					save();
    				} else {
    					JOptionPane.showMessageDialog(frame, "Personen finns redan inlagd!");
    				}
    			}
    		}
    		else if(e.getSource() == changeClub) {
    			StringTokenizer inString = new StringTokenizer(inputNameLabel.getText(), ",");
    			String labelName = inString.nextToken();
    			String labelClub = inString.nextToken().trim();
    			String newClub = JOptionPane.showInputDialog(frame, "Skriv in ny klubb", labelClub);
    			if(newClub != null && newClub.trim() != "") {
    				if(name.add(labelName, newClub)) {
    					name.remove(labelName, labelClub);
    					name.sortedNames();
    					updatePersonMatch();
    					Integer personID = (Integer) personTracker.get(labelName + ", " + labelClub);
    					personTracker.remove(labelName + ", " + labelClub);
    					personTracker.put(labelName + ", " + newClub, personID);
    					personNameTracker.put(personID, labelName + ", " + newClub);
    					inputNameLabel.setText(labelName + ", " + newClub);
    					resultInput.updateNameAndClub(labelName, labelClub, labelName, newClub, personID);
    					save();
    				} else {
    					JOptionPane.showMessageDialog(frame, "Personen finns redan inlagd!");
    				}
    			}
    		}
    	}
    	<commit_msg>Fixed a bug which could cause the list of players to be erased.<commit_after>package gui;

import javax.swing.JOptionPane;
import javax.swing.JFrame;
import javax.swing.SwingConstants;
import javax.swing.JPanel;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JTextField;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.UIManager;

import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.KeyAdapter;
import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import javax.swing.ImageIcon;
import java.awt.Image;
import javax.swing.JDialog;
import javax.swing.KeyStroke;
import javax.swing.border.EmptyBorder;

import snitt.SnittWindow;

import datastruct.CompareFile;
import datastruct.AlignmentManager;
import datastruct.Filter;
import datastruct.IOHandler;
import datastruct.NameList;
import datastruct.ResultList;
import datastruct.DataStore;

import java.util.StringTokenizer;

/** klassen som beskriver sjlva huvudfnstret och delen fr skning */
public class SearchWindow {
	private HashMap personTracker;			// hller reda p vem personen r ven om ngon persondata ndras
	private HashMap personNameTracker;		// lagrar namnet som idnumret tillhr
	private NameList name;					// namnlista som anvnds fr skning
	private ResultInputWindow resultInput;	// fnstret fr indata
	private JFrame frame;					// huvudfnster
	private JPanel searchPanel;				// panelen fr skfltet
	private LapSumDialog lapSumDialog; 		// redigeringsfnstret
	private JDialog compInfoDialog;			// indatafnster
	private JTextField searchField,nameField,clubField;	// skflt, namn- och klubbflt fr namnlistan
	public static JTextField STATUSFIELD,MESSAGEFIELD;	// meddelande- och statusflt
	private JButton[] button;							// knapparna med funna personer som matchar skningen
	private JButton addPlayerButton,removePlayerButton;	// lgg till och ta bort spelare
	private JMenuItem newComp, openFromSKV, save;		// meny fr ny tvling och ppna samt spara
	private	JMenuItem saveToHTML, quit, editItem; 		// spara till HTML, avsluta, redigera
	private JMenuItem klassStart, snittStart, about;	// hantera klasser och snittlista, om programmet
	private JMenuItem setLookAndFeel;					// stll in programmets look and feel 
	private JMenuItem makeCompareFile, openCompareFile;	// skapar eller ppnar en jmfrande snittlista
	private JMenuItem headerItem, saveAs, saveAsHTML;	// stter tvlingens namn, spara som fr SKV- och HTML-filer
	private JMenuItem changeName, changeClub;			// ndra namn och klubb p en spelare
	private JMenuItem numberOrientation;				// alternativ fr sifferorienteringen
	private JLabel inputNameLabel;				// innehller namnet p den person som resultat skrivs in fr
	private JFileChooser fileChooser;			// filvljare
	private Filter skvFilter, htmFilter;		// filter fr skv- och htmfiler
	private Filter snittFilter;					// filter fr snittfiler
	private IOHandler io;						// skter skrivning till och lsning frn filer
	private AlignmentManager alignmentManager;	// hller reda p instllningarna fr sifferorientering
	public static boolean SNITTOPEN, KLASSOPEN;	// talar om ifall motsvarande fnster r ppet
	private boolean warningHTM;					// varnar fr att inte skriva till ej nskvrd fil
	private boolean compInfoDialogClosed;		// talar om ifall indatafnstret har stngts ner utan anvndande av knappen Ok
	public static boolean CHANGE;				// hller reda p om ndringar har skett som br sparas
	public static Image ICON;					// programmets ikon
	private KlassWindow klassWindow;			// klasshanterarfnstret
	private SnittWindow snittWindow;			// snittlistshanterarfnstret
	private String compHeader, fileNameSKV, fileNameHTM;// tvlingsrubrik, filnamn fr SKV- och HTML-filerna
	private String fileNameSNITT;				// filnamn fr SNITT-fil
	public static File DIRSKV, DIRHTM, DIRSNITT, DIRJMF;// mappar fr olika filtyper
	public static final int DUMMY_STARTUP = 0;	// antal varv som anges vid "dum"-starten
	private int mode;							// talar om vilket lger som gller
	public static final int MODE_DUMMY = 0;		// heltal fr "dum"-lget
	public static final int MODE_COMP = 1;		// heltal fr lget dr vanlig tvling matas in
	public static final int MODE_SNITT = 2;		// heltal fr lget d man skapar en jmfrande snittlista
	
	/** skapar huvudfnstret */
	public SearchWindow() {
		name = new NameList();
		try {
			name.readNames();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Inlsningen av namnlistan misslyckades", "Varning", JOptionPane.ERROR_MESSAGE);
			name.sortedNames();
		}
		try {
			frame = new JFrame("BangolfResultat");
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Programmet gick ej att starta", "Programfel", JOptionPane.ERROR_MESSAGE);
			System.exit(1);
		}
		try {
			ImageIcon frameIcon = new ImageIcon("data/brikon.gif");
			ICON = frameIcon.getImage();
			frame.setIconImage(ICON);
		} catch (Exception e) {
		}
		compHeader = "";
		fileNameSKV = null;
		fileNameHTM = null;
		warningHTM = false;
		CHANGE = false;
		
		alignmentManager = new AlignmentManager();
		if(!alignmentManager.loadOrientation()) {
		    JOptionPane.showMessageDialog(null, "Tidigare sifferorienteringsinstllningar gick ej att lsa in",
                    "Varning", JOptionPane.ERROR_MESSAGE);
		}
		
		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		WindowHandler window = new WindowHandler();
		frame.addWindowListener(window);
		
		searchPanel = new JPanel();
		searchPanel.setBorder(new EmptyBorder(5,5,5,5));
		button = new JButton[10];
		
		JLabel[] searchLabel = new JLabel[6];
		searchLabel[0] = new JLabel("Registrera, ndra eller ta bort resultat");
		searchLabel[1] = new JLabel("genom att ska upp spelaren i detta flt");
		searchLabel[2] = new JLabel("och sedan klicka p knappen med namnet:");
		searchLabel[3] = new JLabel("ndra i det skbara namnregistret:");
		searchLabel[4] = new JLabel("Namn:");
		searchLabel[5] = new JLabel("Klubb:");
		for(int i = 0; i < 4; i++) {
			searchLabel[i].setPreferredSize(new Dimension(250,15));
		}
		searchLabel[4].setPreferredSize(new Dimension(120,15));
		searchLabel[5].setPreferredSize(new Dimension(120,15));
		
		KeyHandler keyhand = new KeyHandler();
		searchField = new JTextField();
		searchField.setPreferredSize(new Dimension(240,20));
		searchField.addKeyListener(keyhand);
		
		nameField = new JTextField();
		nameField.setPreferredSize(new Dimension(120,20));
		clubField = new JTextField();
		clubField.setPreferredSize(new Dimension(120,20));
		GridBagLayout gridbag = new GridBagLayout();
		GridBagConstraints c = new GridBagConstraints();
		searchPanel.setLayout(gridbag);
		c.fill = GridBagConstraints.BOTH;
		c.insets = new Insets(0,1,0,1);
		c.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints(searchLabel[0], c);
		gridbag.setConstraints(searchLabel[1], c);
		gridbag.setConstraints(searchLabel[2], c);
		c.insets = new Insets(1,1,1,1);
		gridbag.setConstraints(searchField, c);
		gridbag.setConstraints(searchLabel[3], c);
		searchPanel.add(searchLabel[0]);
		searchPanel.add(searchLabel[1]);
		searchPanel.add(searchLabel[2]);
		searchPanel.add(searchField);
		
		SearchHandler searchHand = new SearchHandler();
		ButtonKeyHandler buttonHand = new ButtonKeyHandler();
		int key = KeyEvent.VK_0;
		for(int i = 0; i < 10; i++) {
			button[i] = new JButton();
			button[i].setMnemonic(key);
			key++;
			button[i].setPreferredSize(new Dimension(240,25));
			button[i].setHorizontalAlignment(SwingConstants.LEFT);
			button[i].setFocusable(false);
			button[i].addActionListener(searchHand);
			button[i].addKeyListener(buttonHand);
			gridbag.setConstraints(button[i], c);
			searchPanel.add(button[i]);
		}
		JLabel emptyLabel = new JLabel(" ");
		gridbag.setConstraints(emptyLabel, c);
		searchPanel.add(emptyLabel);
		c.gridwidth = 1;
		c.insets = new Insets(1,1,1,2);
		gridbag.setConstraints(searchLabel[4], c);
		c.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints(searchLabel[5], c);
		c.gridwidth = 1;
		gridbag.setConstraints(nameField, c);
		c.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints(clubField, c);
		c.gridwidth = 1;
		addPlayerButton = new JButton("Lgg till");
		addPlayerButton.setMnemonic(KeyEvent.VK_L);
		addPlayerButton.setPreferredSize(new Dimension(120,25));
		removePlayerButton = new JButton("Ta bort");
		removePlayerButton.setMnemonic(KeyEvent.VK_T);
		removePlayerButton.setPreferredSize(new Dimension(120,25));
		PlayerHandler playHand = new PlayerHandler();
		addPlayerButton.addActionListener(playHand);
		addPlayerButton.addKeyListener(buttonHand);
		removePlayerButton.addActionListener(playHand);
		removePlayerButton.addKeyListener(buttonHand);
		gridbag.setConstraints(addPlayerButton, c);
		c.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints(removePlayerButton, c);
		searchPanel.add(searchLabel[3]);
		searchPanel.add(searchLabel[4]);
		searchPanel.add(searchLabel[5]);
		searchPanel.add(nameField);
		searchPanel.add(clubField);
		searchPanel.add(addPlayerButton);
		searchPanel.add(removePlayerButton);
		
		JMenuBar bar = new JMenuBar();
		JMenu menu = new JMenu("Arkiv");
		menu.setMnemonic(KeyEvent.VK_A);
		JMenu edit = new JMenu("Redigera");
		edit.setMnemonic(KeyEvent.VK_R);
		JMenu klassMenu = new JMenu("Klasser");
		klassMenu.setMnemonic(KeyEvent.VK_K);
		JMenu snittMenu = new JMenu("Snittlistor");
		snittMenu.setMnemonic(KeyEvent.VK_S);
		JMenu windowMenu = new JMenu("Fnster");
		windowMenu.setMnemonic(KeyEvent.VK_F);
		JMenu help = new JMenu("Info");
		help.setMnemonic(KeyEvent.VK_I);
		bar.add(menu);
		bar.add(edit);
		bar.add(klassMenu);
		bar.add(snittMenu);
		bar.add(windowMenu);
		bar.add(help);
		MenuHandler menuHand = new MenuHandler();
		newComp = new JMenuItem("Ny tvling...", KeyEvent.VK_N);
		newComp.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
		openFromSKV = new JMenuItem("ppna tvling...", KeyEvent.VK_P);
		openFromSKV.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, ActionEvent.CTRL_MASK));
		save = new JMenuItem("Spara", KeyEvent.VK_S);
		save.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, ActionEvent.CTRL_MASK));
		save.setEnabled(false);
		saveAs = new JMenuItem("Spara som...", KeyEvent.VK_M);
		saveAs.setEnabled(false);
		saveToHTML = new JMenuItem("Skapa webbsida", KeyEvent.VK_W);
		saveToHTML.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_W, ActionEvent.CTRL_MASK));
		saveToHTML.setEnabled(false);
		saveAsHTML = new JMenuItem("Skapa webbsida som...", KeyEvent.VK_B);
		saveAsHTML.setEnabled(false);
		quit = new JMenuItem("Avsluta", KeyEvent.VK_A);
		headerItem = new JMenuItem("Ange tvlingens rubrik...", KeyEvent.VK_R);
		headerItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, ActionEvent.CTRL_MASK));
		headerItem.setEnabled(false);
		editItem = new JMenuItem("Delsummor och placering...", KeyEvent.VK_D);
		editItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK));
		editItem.setEnabled(false);
		numberOrientation = new JMenuItem("Sifferorientering...", KeyEvent.VK_O);
		numberOrientation.setEnabled(false);
		klassStart = new JMenuItem("Hantera klasser...", KeyEvent.VK_H);
		klassStart.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ActionEvent.CTRL_MASK));
		snittStart = new JMenuItem("Hantera snittlistor...", KeyEvent.VK_H);
		snittStart.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, ActionEvent.CTRL_MASK));
		makeCompareFile = new JMenuItem("Ny jmfrande snittlista...", KeyEvent.VK_N);
		openCompareFile = new JMenuItem("ppna jmfrande snittlista...", KeyEvent.VK_P);
		setLookAndFeel = new JMenuItem("Vlj utseende och knsla...", KeyEvent.VK_U);
		about = new JMenuItem("Om BangolfResultat...", KeyEvent.VK_O);
		newComp.addActionListener(menuHand);
		saveToHTML.addActionListener(menuHand);
		saveAsHTML.addActionListener(menuHand);
		saveAs.addActionListener(menuHand);
		save.addActionListener(menuHand);
		openFromSKV.addActionListener(menuHand);
		quit.addActionListener(menuHand);
		headerItem.addActionListener(menuHand);
		editItem.addActionListener(menuHand);
		numberOrientation.addActionListener(menuHand);
		klassStart.addActionListener(menuHand);
		snittStart.addActionListener(menuHand);
		makeCompareFile.addActionListener(menuHand);
		openCompareFile.addActionListener(menuHand);
		setLookAndFeel.addActionListener(menuHand);
		about.addActionListener(menuHand);
		menu.add(newComp);
		menu.add(openFromSKV);
		menu.addSeparator();
		menu.add(save);
		menu.add(saveAs);
		menu.add(saveToHTML);
		menu.add(saveAsHTML);
		menu.addSeparator();
		menu.add(quit);
		edit.add(headerItem);
		edit.addSeparator();
		edit.add(editItem);
		edit.add(numberOrientation);
		klassMenu.add(klassStart);
		snittMenu.add(snittStart);
		snittMenu.addSeparator();
		snittMenu.add(makeCompareFile);
		snittMenu.add(openCompareFile);
		windowMenu.add(setLookAndFeel);
		help.add(about);
		frame.setJMenuBar(bar);
		
		JMenuBar resBar = new JMenuBar();
		JMenu resMenu = new JMenu("Redigera");
		resMenu.setMnemonic(KeyEvent.VK_R);
		resBar.add(resMenu);
		changeName = new JMenuItem("ndra namn...", KeyEvent.VK_N);
		changeName.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
		changeClub = new JMenuItem("ndra klubb...", KeyEvent.VK_K);
		changeClub.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_K, ActionEvent.CTRL_MASK));
		changeName.addActionListener(menuHand);
		changeClub.addActionListener(menuHand);
		resMenu.add(changeName);
		resMenu.add(changeClub);
		
		io = new IOHandler();
		try {
			personTracker = (HashMap) io.load("ptrack");
		} catch (Exception e) {
			personTracker = new HashMap();
			personTracker.put(" ", new Integer(0));
		}
		try {
			personNameTracker = (HashMap) io.load("pnametrack");
		} catch (Exception e) {
			personNameTracker = new HashMap();
		}
		
		JPanel statusPanel = new JPanel();
		statusPanel.setLayout(new BorderLayout());
		MESSAGEFIELD = new JTextField("Starta ny tvling genom att klicka p Arkiv -> Ny tvling...");
		MESSAGEFIELD.setEditable(false);
		MESSAGEFIELD.setFocusable(false);
		STATUSFIELD = new JTextField();
		STATUSFIELD.setEditable(false);
		STATUSFIELD.setHorizontalAlignment(JTextField.CENTER);
		STATUSFIELD.setPreferredSize(new Dimension(20,10));
		STATUSFIELD.setFocusable(false);
		statusPanel.add(MESSAGEFIELD, BorderLayout.CENTER);
		statusPanel.add(STATUSFIELD, BorderLayout.WEST);
		resultInput = new ResultInputWindow(frame, resBar, personTracker, personNameTracker);
		lapSumDialog = new LapSumDialog(frame);
		compInfoDialog = new CompInfoDialog(frame, this);
		compInfoDialog.addWindowListener(new WinHandForCompInfoDialog());
		
		fileChooser = new JFileChooser();
		skvFilter = new Filter(new String[]{"skv"}, "Semikolonseparerad fil");
		htmFilter = new Filter(new String[]{"htm", "html"}, "Webbsida");
		snittFilter = new Filter(new String[]{"snitt"}, "Jmfrelsefil fr snittlista");
		try {
			DIRSKV = (File) io.load("dirskv");
			DIRHTM = (File) io.load("dirhtm");
			DIRSNITT = (File) io.load("dirsnitt");
			DIRJMF = (File) io.load("dirjmf");
		} catch (Exception e) {
			DIRSKV = null;
			DIRHTM = null;
			DIRSNITT = null;
			DIRJMF = null;
		}
		
		frame.getContentPane().add(searchPanel, BorderLayout.WEST);
		frame.getContentPane().add(statusPanel, BorderLayout.SOUTH);
		dummyStartUp();
		frame.pack();
		frame.setVisible(true);
	}
	
	/** fixar till menyalternativen fr skapandet av en jmfrelsesnittlista */
	private void enableCompareFileMenus() {
	    headerItem.setEnabled(false);
		editItem.setEnabled(false);
		numberOrientation.setEnabled(false);
	    save.setEnabled(true);
		saveAs.setEnabled(true);
		saveToHTML.setEnabled(false);
		saveAsHTML.setEnabled(false);
	}
	
	/** gr menyalternativen under Redigera och de olika alternativen fr att spara tillgngliga */
	private void enableDisabledMenus() {
	    headerItem.setEnabled(true);
		editItem.setEnabled(true);
		numberOrientation.setEnabled(true);
	    save.setEnabled(true);
		saveAs.setEnabled(true);
		saveToHTML.setEnabled(true);
		saveAsHTML.setEnabled(true);
		setMode(SearchWindow.MODE_COMP, null);
	}
	
	/** stller lget till mode, alternativen r MODE_COMP, MODE_DUMMY och MODE_SNITT 
	 * 	skickar med ett objekt o som anvnds vid vissa tillfllen */
	private void setMode(int mode, Object o) {
	    int oldMode = this.mode;
	    this.mode = mode;
	    if(mode == SearchWindow.MODE_SNITT) {
	        CompareFile compareFile = (CompareFile) o;
	        if(compareFile == null) {
	            compareFile = new CompareFile(newCompareFile());
	        }
	        if(compareFile.getSurface() != -1) {
	            resultInput.setCompareFile(compareFile);
	            resultInput.setupResultInputPanel(mode);
	        } else {
	            this.mode = oldMode;
	        }
	    }
	}
	
	/** startar upp saker fr att skapa en jmfrelsesnittlista */
	private int newCompareFile() {
	    int surface = -1;
	    int val = JOptionPane.YES_OPTION;
		if(CHANGE) {
			val = JOptionPane.showConfirmDialog(frame, "De senaste ndringarna r ej sparade. Vill du spara nu?"
			, "Spara?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
			if(val == JOptionPane.YES_OPTION) {
				autoSave();
			}
		}
		if(!CHANGE || val == JOptionPane.NO_OPTION) {
		    String[] possibleValues = { "Filt", "EB", "Betong", "Blandad" };
		    String selectedValue = (String) JOptionPane.showInputDialog(frame, "Vlj underlag", "Indata", 
		            JOptionPane.INFORMATION_MESSAGE, null, possibleValues, possibleValues[0]);
			if(selectedValue != null) {
	            if(selectedValue.equals(possibleValues[0])) {
	                surface = ResultList.FILT;
	            } else if(selectedValue.equals(possibleValues[1])) {
	                surface = ResultList.EB;
	            } else if(selectedValue.equals(possibleValues[2])) {
	                surface = ResultList.BETONG;
	            } else if(selectedValue.equals(possibleValues[3])) {
	                surface = SnittWindow.BLANDAD;
	            }
				compHeader = "";
				fileNameSKV = null;
				fileNameHTM = null;
				fileNameSNITT = null;
				warningHTM = false;
				CHANGE = false;
				STATUSFIELD.setText("");
				MESSAGEFIELD.setText("Ny jmfrelsesnittlista har ppnats.");
				ScoreBoardWindow.setHeader(compHeader);
				inputNameLabel = resultInput.getNameLabel();
				enableCompareFileMenus();
			}
		}
		return surface;
	}
	
	/** ppnar en ny tvling bara fr att f igng programmet korrekt */
	private void dummyStartUp() {
	    setMode(SearchWindow.MODE_DUMMY, null);
	    ResultInputWindow.RESULTLIST = new ResultList(2, 0, new boolean[]{false, false});
		ResultInputWindow.BOARD = new ScoreBoardWindow(ResultInputWindow.RESULTLIST);
		frame.getContentPane().add(ResultInputWindow.BOARD.getScrollPane(), BorderLayout.CENTER);
		resultInput.setupResultInputPanel(MODE_DUMMY);
		inputNameLabel = resultInput.getNameLabel();
	}
	
	/** stller in resultatinmatningsfnstret och fnstret fr delsummor, init r true om 
	 *  ingen ny resultatlista behver skapas, boxData[0] talar om ifall startnummer skall vara med,
	 *  boxData[1] sger om licensnummer skall vara med, nbrRounds r antal varv och surface anger
	 *  tvlingens underlag */
	protected void setupResultInputPanel(boolean init, boolean[] boxData, int nbrRounds, int surface) {
	    resultInput.setupResultInputPanel(init, boxData, nbrRounds, surface);
	    lapSumDialog.setNbrRounds(nbrRounds);
	    lapSumDialog.setEditData(new boolean[nbrRounds-1]);
	}
	
	/** uppdaterar skresultaten */
	private void updatePersonMatch() {
		String search = searchField.getText();
		String[] names = name.getNames(search);
		for(int i = 0; i < 10; i++) {
			if(names[i] != null) {
				button[i].setFocusable(true);
				button[i].setText(i + ". " + names[i]);
			}
			else {
				button[i].setFocusable(false);
				button[i].setText("");
			}
		}
	}
	
	/** skter om avslutandet av programmet */
	private void exit() {
		int val = JOptionPane.YES_OPTION;
		if(CHANGE) {
			val = JOptionPane.showConfirmDialog(frame, "De senaste ndringarna r ej sparade. Vill du spara nu?"
			, "Spara?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
			if(val == JOptionPane.YES_OPTION) {
				autoSave();
			}
		}
		if(!CHANGE || val == JOptionPane.NO_OPTION) {
			if(SNITTOPEN) {
				snittWindow.exit();
			}
			if(KLASSOPEN) {
				klassWindow.exit();
			}
			save();
			System.exit(0);
		}
	}
	
	/** sparar filer som programmet anvnder sig av */
	private void save() {
	    if(!alignmentManager.saveOrientation()) {
	        JOptionPane.showMessageDialog(frame, "Orienteringsinstllningarna gick ej att spara",
                    "Varning", JOptionPane.ERROR_MESSAGE);
	    }
		try {
			io.save("licensemap", resultInput.getLicenseMap());
			io.save("licensenamemap", resultInput.getLicenseIDMap());
		} catch (Exception e) {
			JOptionPane.showMessageDialog(frame, "Listan ver licensnummer gick ej att spara", "Varning", JOptionPane.ERROR_MESSAGE);
		}
		try {
			name.writeNames();
		} catch (Exception e) {
			JOptionPane.showMessageDialog(frame, "Namnlistan gick ej att spara", "Varning", JOptionPane.ERROR_MESSAGE);
		}
		try {
			io.save("dirskv", DIRSKV);
			io.save("dirhtm", DIRHTM);
			io.save("dirsnitt", DIRSNITT);
			io.save("dirjmf", DIRJMF);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(frame, "Senast anvnda mappar gick ej att spara", "Varning", JOptionPane.ERROR_MESSAGE);
		}
		try {
			io.save("ptrack", personTracker);
			io.save("pnametrack", personNameTracker);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(frame, "Intern ID-lista gick ej att spara", "Varning", JOptionPane.ERROR_MESSAGE);
		}
	}
	
	/** sparar efter uppmaning */
	private void autoSave() {
		MenuHandler menu = new MenuHandler();
		if(mode == MODE_COMP) {
		    menu.saveToSKV();
		} else if(mode == MODE_SNITT) {
		    menu.saveToSNITT();
		}
	}
	
	/** talar om fr resultatinmatningsfnstret vilken person som valts */
	private void setPopup(JButton b) {
	    searchField.selectAll();
		searchField.requestFocus();
		resultInput.setPopup(b, mode);
	}

    /** lgger till och tar bort personen frn namnlistan, lgger till om add r true */
	private void handlePlayer(boolean add) {
		boolean done = false;
		boolean visit = false;
		int confirmValue =  JOptionPane.NO_OPTION;
		String nameString = nameField.getText().trim();
		String clubString = clubField.getText().trim();
		if(!nameString.equals("") && !clubString.equals("")) {
			if(add) {
				done = name.add(nameString, clubString);
				if(done) {
					addPerson(nameString + ", " + clubString);
				}
				name.sortedNames();
				visit = true;
			} else {
			    if(name.containsPerson(nameString, clubString)) {
			        confirmValue = JOptionPane.showConfirmDialog(frame, "r du sker p att du vill ta bort "
			                + nameString + ", " + clubString + ", permanent?");
			        if(confirmValue == JOptionPane.YES_OPTION) {
			            done = name.remove(nameString, clubString);
			            if(done) {
			                resultInput.removeFromLicenseMap((Integer) personTracker.get(nameString + 
			                        ", " + clubString));
			            }
			            name.sortedNames();
			            visit = true;
			        } else if (confirmValue == JOptionPane.NO_OPTION) {
			            nameField.setText("");
			            clubField.setText("");
			        }
			    } else {
			        visit = true;
			    }
			}
		} else {
			JOptionPane.showMessageDialog(frame, "Flten mste innehlla mer n blanksteg!");
		}
		if(done && visit) {
			if(!add) {
				updatePersonMatch();
				save();
				MESSAGEFIELD.setText(nameString + ", " + clubString + ", r nu borttagen frn skningsfltet.");
			} else {
				updatePersonMatch();
				save();
				MESSAGEFIELD.setText(nameString + ", " + clubString + ", har nu lagts till i skningsfltet.");
			}
			nameField.setText("");
			clubField.setText("");
		} else if(visit) {
		    if(!add) {
		        JOptionPane.showMessageDialog(frame, nameString + ", " + clubString + 
		        ", gick inte att ta bort frn skningsfltet. Kolla s att rtt namn och klubb r angiven.");		        
		    } else {
		        JOptionPane.showMessageDialog(frame, nameString + ", " + clubString + 
		        ", gick inte att lgga till i skningsfltet. Kolla s att personen inte redan finns dr.");
		    }
		}
	}
	
	/** lgger till personen identity i listan ver idnummer */
	private void addPerson(String identity) {
		Integer i = (Integer) personTracker.get(" ");
		personTracker.put(identity, i);
		personNameTracker.put(i, identity);
		personTracker.put(" ", new Integer(i.intValue() + 1));
	}
	
	/** loggar informationen om Throwable throwable */
	private static void logError(Throwable throwable) {
	    JOptionPane.showMessageDialog(null, "Ett fel i programmet har uppsttt. " +
        		"Informationen om detta sparas i filen error.log.\n" +
        		"Denna fil finns i katalogen dr programmet installerades, " +
        		"vanligtvis C:\\Program\\BangolfResultat.\n\n" +
        		"Var vnlig spara aktivt arbete och starta om programmet.\n" +
        		"Om problem uppstr igen tag kontakt med programmets tillverkare.",
        		"Varningsmeddelande", JOptionPane.WARNING_MESSAGE);
	    if(IOHandler.logError(throwable)) {
	        JOptionPane.showMessageDialog(null, "Loggningen r klar.");
	    } else {
	        JOptionPane.showMessageDialog(null, "Loggningen misslyckades.");
	    }
	}
	
	/** mainmetoden som startar hela programmet */
	public static void main(String[] args) {
	    System.setProperty("sun.awt.exception.handler", "gui.SearchWindow$ErrorHandler");
	    
	    Object lookAndFeel = DataStore.get(DataStore.LOOK_AND_FEEL);
	    try {
	    	if (lookAndFeel != null) {
	    		UIManager.setLookAndFeel((String) lookAndFeel);
	    	}
	    } catch (Exception e) {
	    	//e.printStackTrace();
	    }
	    
	    new SearchWindow();
	}

    /** klassen som tar hand om knapptryckningarna i menyn */
    class MenuHandler implements ActionListener {
    	/** kollar vilket menyalternativ som valts och utfr lmplig handling */
    	public void actionPerformed(ActionEvent e) {
    		if(e.getSource() == saveToHTML) {
    			if(fileNameHTM == null) {
    				saveAsHTML();
    			} else {
    				try {
    					boolean doit = true;
    					if(warningHTM) {
    						int val = JOptionPane.showConfirmDialog(frame, "Vill du att webbsidan sparas till filen " + fileNameHTM + "?"
    						, "Spara webbsida", JOptionPane.YES_NO_OPTION);
    						if(val != JOptionPane.YES_OPTION) {
    							doit = false;
    						}
    					}
    					if(doit) {
    					    int align = AlignmentManager.getOrientation(AlignmentWindow.COMP_OWNER);
    						io.outputToHTML(fileNameHTM, resultInput.getResultList(), compHeader, align);
    						warningHTM = false;
    						MESSAGEFIELD.setText("Tvlingen r sparad som webbsida.");
    					} else {
    						saveAsHTML();
    					}
    				} catch (Exception f) {
    					JOptionPane.showMessageDialog(frame, "Skrivning till HTML-fil misslyckades", "Varning", JOptionPane.ERROR_MESSAGE);
    				}
    			}
    		}
    		else if(e.getSource() == saveAsHTML) {
    			saveAsHTML();
    		}
    		else if(e.getSource() == save) {
    		    if(mode == MODE_COMP) {
    		        saveToSKV();
    		    } else if(mode == MODE_SNITT) {
    		        saveToSNITT();
    		    }
    		}
    		else if(e.getSource() == saveAs) {
    		    if(mode == MODE_COMP) {
    		        saveAsSKV();
    		    } else if(mode == MODE_SNITT) {
    		        saveAsSNITT();
    		    }
    		}
    		else if(e.getSource() == openFromSKV) {
    			int val = JOptionPane.YES_OPTION;
    			if(CHANGE) {
    				val = JOptionPane.showConfirmDialog(frame, "De senaste ndringarna r ej sparade. Vill du spara nu?"
    				, "Spara?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    				if(val == JOptionPane.YES_OPTION) {
    					autoSave();
    				}
    			}
    			if(!CHANGE || val == JOptionPane.NO_OPTION) {
    				fileChooser.setCurrentDirectory(DIRSKV);
    				fileChooser.setSelectedFile(new File(""));
    				fileChooser.setFileFilter(skvFilter);
    				int retval = fileChooser.showOpenDialog(frame);
    				if(retval == JFileChooser.APPROVE_OPTION) {
    					File file = fileChooser.getSelectedFile();
    					DIRSKV = fileChooser.getCurrentDirectory();
    					fileNameSKV = file.getPath();
    					if(!fileNameSKV.endsWith(".skv")) {
    						fileNameSKV = fileNameSKV + ".skv";
    					}
    					if(new File(fileNameSKV).exists()) {
    					    try {
    					        Object[] o = io.inputFromSKV(fileNameSKV);
    					        compHeader = (String)o[0];
    					        fileNameHTM = (String)o[1];
    					        warningHTM = true;
    					        ResultList result = (ResultList) o[2];
    					        resultInput.init(result);
    					        resultInput.setStartNbrMap((HashMap)o[3]);
    					        lapSumDialog.setNbrRounds(result.getNbrRounds());
    					        lapSumDialog.setEditData((boolean[])o[4]);
    					        ScoreBoardWindow.setHeader(compHeader);
    					        inputNameLabel = resultInput.getNameLabel();
    					        CHANGE = false;
    					        STATUSFIELD.setText("");
    					        MESSAGEFIELD.setText("ppnat filen: " + fileNameSKV + ".");
    					        enableDisabledMenus();
    					    } catch (Exception f) {
    					        JOptionPane.showMessageDialog(frame, "Inlsningen frn SKV-fil misslyckades", "Varning", JOptionPane.ERROR_MESSAGE);
    					    }
    					} else {
    					    JOptionPane.showMessageDialog(frame, "Filen, " + fileNameSKV + ", existerar inte", "Varning", JOptionPane.ERROR_MESSAGE);
    					}
    				}
    			}
    		}
    		else if(e.getSource() == newComp) {
    			int val = JOptionPane.YES_OPTION;
    			if(CHANGE) {
    				val = JOptionPane.showConfirmDialog(frame, "De senaste ndringarna r ej sparade. Vill du spara nu?"
    				, "Spara?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    				if(val == JOptionPane.YES_OPTION) {
    					autoSave();
    				}
    			}
    			if(!CHANGE || val == JOptionPane.NO_OPTION) {
    				compInfoDialog.setLocationRelativeTo(frame);
    				compInfoDialog.setVisible(true);
    				if(!compInfoDialogClosed) {
    					compHeader = "";
    					fileNameSKV = null;
    					fileNameHTM = null;
    					warningHTM = false;
    					CHANGE = false;
    					STATUSFIELD.setText("");
    					MESSAGEFIELD.setText("Ny tvling har ppnats.");
    					ScoreBoardWindow.setHeader(compHeader);
    					inputNameLabel = resultInput.getNameLabel();
    					enableDisabledMenus();
    				} else {
    					compInfoDialogClosed = false;
    				}
    			}
    		}
    		else if(e.getSource() == editItem) {
    			lapSumDialog.setEditWindow();
    			lapSumDialog.getContentPane().add(lapSumDialog.lapSumPanel(), BorderLayout.NORTH);
    			lapSumDialog.pack();
    			lapSumDialog.setLocationRelativeTo(frame);
    			lapSumDialog.setVisible(true);
    		}
    		else if(e.getSource() == headerItem) {
    			String tempHeader = JOptionPane.showInputDialog(frame, "Skriv in rubriken fr tvlingen", ScoreBoardWindow.getHeader());
    			if(tempHeader != null) {
    				compHeader = tempHeader;
    				ScoreBoardWindow.setHeader(compHeader);
    				CHANGE = true;
    				STATUSFIELD.setText("*");
    				MESSAGEFIELD.setText("");
    			}
    		}
    		else if(e.getSource() == numberOrientation) {
    		    new AlignmentWindow(frame, AlignmentWindow.COMP_OWNER, alignmentManager);
    		}
    		else if(e.getSource() == klassStart) {
    			if(!KLASSOPEN) {
    				KLASSOPEN = true;
    				klassWindow = new KlassWindow(frame);
    			} else {
    				klassWindow.setVisible(true);
    			}
    		}
    		else if(e.getSource() == snittStart) {
    			if(!SNITTOPEN) {
    				SNITTOPEN = true;
    				snittWindow = new SnittWindow(frame, personNameTracker, alignmentManager);
    			} else {
    				snittWindow.setVisible(true);
    			}
    		}
    		/** ppnar fnster fr att mata in en jmfrelsesnittlista */
			else if(e.getSource() == makeCompareFile) {
			    setMode(SearchWindow.MODE_SNITT, null);
			}
			else if(e.getSource() == openCompareFile) {
    			int val = JOptionPane.YES_OPTION;
    			if(CHANGE) {
    				val = JOptionPane.showConfirmDialog(frame, "De senaste ndringarna r ej sparade. Vill du spara nu?"
    				, "Spara?", JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
    				if(val == JOptionPane.YES_OPTION) {
    					autoSave();
    				}
    			}
    			if(!CHANGE || val == JOptionPane.NO_OPTION) {
    				fileChooser.setCurrentDirectory(DIRJMF);
    				fileChooser.setSelectedFile(new File(""));
    				fileChooser.setFileFilter(snittFilter);
    				int retval = fileChooser.showOpenDialog(frame);
    				if(retval == JFileChooser.APPROVE_OPTION) {
    					File file = fileChooser.getSelectedFile();
    					DIRJMF = fileChooser.getCurrentDirectory();
    					fileNameSNITT = file.getPath();
    					if(!fileNameSNITT.endsWith(".snitt")) {
    						fileNameSNITT = fileNameSNITT + ".snitt";
    					}
    					if(new File(fileNameSNITT).exists()) {
    					    try {
    					        CompareFile compareFile = io.inputFromSNITT(fileNameSNITT);
    					        setMode(MODE_SNITT, compareFile);
    					        CHANGE = false;
    					        STATUSFIELD.setText("");
    					        MESSAGEFIELD.setText("ppnat filen: " + fileNameSNITT + ".");
    					        enableCompareFileMenus();
    					    } catch (IOException ioe) {
    					        JOptionPane.showMessageDialog(frame, "Inlsningen frn SNITT-fil misslyckades", "Varning", JOptionPane.ERROR_MESSAGE);
    					    }
    					} else {
    					    JOptionPane.showMessageDialog(frame, "Filen, " + fileNameSNITT + ", existerar inte", "Varning", JOptionPane.ERROR_MESSAGE);
    					}
    				}
    			}
	    	}
			else if(e.getSource() == setLookAndFeel) {
				String java = "Java";
				String system = "Naturlig";
				String initialSelectionValue = java;
				Object lookAndFeel = DataStore.get(DataStore.LOOK_AND_FEEL);
				if (lookAndFeel != null) {
					if (((String) lookAndFeel).equals(
							UIManager.getSystemLookAndFeelClassName())) {
						initialSelectionValue = system;
					}
				}
				String newLookAndFeel = (String) JOptionPane.showInputDialog(
						frame, "Vlj utseende och knsla:\n(Brjar glla nr BangolfResultat har startats om.)",
						"Utseende och knsla", JOptionPane.INFORMATION_MESSAGE,
						null, new String[]{java,system}, initialSelectionValue);
				if (newLookAndFeel != null) {
					if (newLookAndFeel.equals(java)) {
						DataStore.set(DataStore.LOOK_AND_FEEL, UIManager.getCrossPlatformLookAndFeelClassName());
					} else if (newLookAndFeel.equals(system)) {
						DataStore.set(DataStore.LOOK_AND_FEEL, UIManager.getSystemLookAndFeelClassName());
					}
				}
			}
    		else if(e.getSource() == about) {
    			new AboutWindow(frame);
    		}
    		else if(e.getSource() == quit) {
    			exit();
    		}
    		else if(e.getSource() == changeName) {
    			StringTokenizer inString = new StringTokenizer(inputNameLabel.getText(), ",");
    			String labelName = inString.nextToken();
    			String labelClub = inString.nextToken().trim();
    			String newName = JOptionPane.showInputDialog(frame, "Skriv in nytt namn", labelName);
    			if(newName != null && !newName.trim().equals("")) {
    				if(name.add(newName, labelClub)) {
    					name.remove(labelName, labelClub);
    					name.sortedNames();
    					updatePersonMatch();
    					Integer personID = (Integer) personTracker.get(labelName + ", " + labelClub);
    					personTracker.remove(labelName + ", " + labelClub);
    					personTracker.put(newName + ", " + labelClub, personID);
    					personNameTracker.put(personID, newName + ", " + labelClub);
    					inputNameLabel.setText(newName + ", " + labelClub);
    					resultInput.updateNameAndClub(labelName, labelClub, newName, labelClub, personID);
    					save();
    				} else {
    					JOptionPane.showMessageDialog(frame, "Personen finns redan inlagd!");
    				}
    			}
    		}
    		else if(e.getSource() == changeClub) {
    			StringTokenizer inString = new StringTokenizer(inputNameLabel.getText(), ",");
    			String labelName = inString.nextToken();
    			String labelClub = inString.nextToken().trim();
    			String newClub = JOptionPane.showInputDialog(frame, "Skriv in ny klubb", labelClub);
    			if(newClub != null && !newClub.trim().equals("")) {
    				if(name.add(labelName, newClub)) {
    					name.remove(labelName, labelClub);
    					name.sortedNames();
    					updatePersonMatch();
    					Integer personID = (Integer) personTracker.get(labelName + ", " + labelClub);
    					personTracker.remove(labelName + ", " + labelClub);
    					personTracker.put(labelName + ", " + newClub, personID);
    					personNameTracker.put(personID, labelName + ", " + newClub);
    					inputNameLabel.setText(labelName + ", " + newClub);
    					resultInput.updateNameAndClub(labelName, labelClub, labelName, newClub, personID);
    					save();
    				} else {
    					JOptionPane.showMessageDialog(frame, "Personen finns redan inlagd!");
    				}
    			}
    		}
    	}
    	
{'fraction_non_alphanumeric': 0.11746755150449081, 'fraction_numerical': 0.003331467711414941, 'mean_word_length': 3.3977379278012187, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2446646', 'n_tokens_mistral': 28026, 'n_tokens_neox': 25032, 'n_words': 4856}