#! /opt/gensoft/adm/bin/perl
use lib "/opt/gensoft/exe/alohomora/v0.36/lib/perl5";
#
# ALOHOMORA.PL
#
# Quality Control and Data Conversion of SNP Array Genotypes for Gene Mapping Projects
# Copyright (c) Franz Rschendorf 2003-2009
#
# Modifications:
# 21-Sep-2004, clean up code, delete test functions
# 25-Aug-2004, calculate allele frequencies for x-linked SNPs
# 24-Sep-2004, clean up code FR
# 01-Nov-2004, Kosambi function
# 03-Jan-2005, new GDAS-format, convert TSC-number (TSC1234 -> tsc0001234)
# 05-Feb-2005, Compare sample IDs in pedfile.pro with GDAS genotype file
# 20-Feb-2005, PedStat, Pedigree statistics 
# 08-May-2005, read QTL file
# 26-Jun-2005, write Linkage format QTL files
# 09-Sep-2005, PedCheck, PlotPedCheckErr bugs
# 16-Oct-2005, genetic map for chips 100K, 500K, Illumina 
# 12-Jan-2006, compare SNPs in genetic map and allele frequency files with genotype file
#              final modifications for v0.29
# 25-Jan-2006, check PedCheck license
# 05-Apr-2006, Haploview with physical map
# 08-Jul-2006, Marker selection for linkage analysis
# 24-Aug-2006, Bug fixed in function PedStat (with alphanumeric sampleIDs)
# 31-Aug-2006, Selection alias name (rs-number) for markers
# 02-Oct-2006, Command line modus
# 18-Nov-2006, Show Help
# 02-Apr-2008, Create Merlin simulation files in GRR-format
# 27-Jul-2009, bug in funktion make directory (no read, write, execute permissions of folder)
# 29-Jul-2009, filters and select markers for linkage analysis
# 30-Oct-2013, when reading marker map program skips all lines with "CHR", but should only skip header-line
# 05-Jun-2014, remove "_Call" in genotype file's headerline 
# 05-Jul-2014, read allele frequencies output
# 05-Jul-2014, remove tsc00000 name correction
# 03-Sep-2014	pedstat: count sex-unknown individuals
# 29-Sep-2016, Compare sampleIDs, sort output
# 30-Mar-2017,  Marker alias name works now with Subset files,

use Tk;
use Cwd;
# use strict;
use File::Copy;
use File::Basename;
use Getopt::Long;
#use TK::BrowseEntry;
#use TK::FileSelect;

###############################  V A R I A B L E S  ############################
my $version="v0.36";

my $mapdir="/opt/gensoft/exe/alohomora/v0.36/share";
# my $map_dir="C:/genetics/affy";			### DOS
# my $map_dir="C:/maps/affy";		# homePC

my $pedfilepro="pedfile.pro";		# Pedigree-Structure for PedCheck and Linkage
my @output=();						# output array TKwindow
my $outfile="";						# Save TKwindow in File or load in editor
my $saveenv="alohomora.ini";

#----- Radiobuttons ----#
my $linked="both";			# autosomal, X-linked or both 
my $chip="Xba142";		# default

#------- Status --------#
my $statusdata=0;	# genotype file loaded = 1
my $statusped=0;	# pedfile.pro loaded = 1
my $statuschk=0;	
my $statusmap=0;	# genetic map loaded = 1
my $statusstat=0;	# Callrate calculation =1
my $statusfreq=0;
my $status_skiplist=0;	# skiplist is loaded = 1
my $status_PedCheckErr=0;	# mendelian errors (pedcheck.all) loaded = 1
my $pchrom="ALL";

#------- Filter --------#
my @skip=();			# Array Skiplist
my @skipextra=();		# Extra Skiplist
my %skiplist=();		# all SNPs from notinf, skipextra, allhomozygous
my $skip_list=0;		# use extra Skiplist
my $skipfile="skiplist.txt";	# skiplist name
my $skip_nopos=1;		# skip SNPs w/o position
my $skip_errors=0;		# skip SNPs with mendelian errors
my $skip_notinf=0;		# skip SNPs non-informative in all samples in all families
my $del_errors=0;		# delete mendelian errors in the family where they occurred
my $del_unlikely=0;		# delete Merlin unlikely errors
my $del_unl_th=0.05;	# delete unlikely genotypes with RATIO < threshold 

#---- Read InFiles -----#
my $infile="";			# GDAS output genotype file
my $basename="";		# Base Filename
my $base_no_ext="";		# Basename no extension
my $dirname=();
my $header="";			# Headerline in genotype file
my @head=();			# Array Headerline
my $snp="";				# SNPname
my %sample=();			# hash, key is column, value is sampleID
my %samples=();			# hash, key is sample ID
my @data=();			# Array Input SNPs & Genotypes
my $FS="_";				# samplename field separator


#------ Pedfilepro -----#
my @pedcheck=();		# Pedigreestructure for Pedcheckfile
my @pedfile=();			# Pedigreestructure for Linkagefile
my $count=0;			# Person Nummer z in Pedfile.pro
my %famlist=();			# Hash all families (key) in Pedfile.pro
my %gender=();			# Hash gender of individuals (key)
my %indiv=();			# hash{$ind}, counts sample IDs 
my @fam=();				# Array family number in pedfile
my @ind=();				# Array sample number in pedfile
my @affind=();			# list of affected individuals (sampleIDs)
my @founder=();			# list of founder individuals
my %member=();			#

#------ QTL file -------#
my $qtlfile="";			# QTL file 
my $qtl_status=0;		# status QTL read in
my $qtl_select=0;		# selection: 1 - use QTL analysis
my %qtlname=();			# names of all QTLs
my %qtltraits=();		# qtl file lines ; key is sampleID 
my $c_traits=0;			# number of quantitative traits in qtlfile

##------- PedCheck ------##
my $pedcheckfile="pedfile.dat";
my $namesfile="names.dat";
my $pedcheckall="pedcheck.all";
my $maxmarker=10000;		# maximal number of SNPs for one run of PedCheck
my @snplist=();			# array SNP list
my %snphet=();			# SNP is heterozygote at affected ind

#---- Hash Genotypes  ----#
my %gtype=();
my @names=();	# replaced with Hash
my %gnames=();	# Hash: names of all SNPs used from genotype file (minus skipped data)

#------ Genetic Markermap  ------#
my $decode_map_131="$map_dir/Xba131_map_decode_2007-01-02.txt";	# Final 10K Xba131
my $marshf_map_131="$map_dir/Xba131_map_marshf_2007-01-02.txt";
my $slm1_map_131="$map_dir/Xba131_map_slm1_2007-01-02.txt";
my $other_map_131="";

my $decode_map_142="$map_dir/Xba142_map_decode_2007-01-02.txt";	# Final 10Kv2 Xba142
my $marshf_map_142="$map_dir/Xba142_map_marshf_2007-01-02.txt";
my $slm1_map_142="$map_dir/Xba142_map_slm1_2007-01-02.txt";
my $other_map_142="";

my $decode_map_240="$map_dir/Xba240_map_decode_2007-01-02.txt";		# 50K Xba240
my $marshf_map_240="$map_dir/Xba240_map_marshf_2007-01-02.txt";
my $slm1_map_240="$map_dir/Xba240_map_slm1_2007-01-02.txt";
my $other_map_240="";	 

my $decode_map_hind="$map_dir/Hind240_map_decode_2007-01-02.txt";	# 50K Hind240
my $marshf_map_hind="$map_dir/Hind240_map_marshf_2007-01-02.txt";
my $slm1_map_hind="$map_dir/Hind240_map_slm1_2007-01-02.txt";
my $other_map_hind="";	 

my $decode_map_nsp="$map_dir/Nsp_map_decode_2007-01-02.txt";		# 250K Nsp
my $marshf_map_nsp="$map_dir/Nsp_map_marshf_2007-01-02.txt";
my $slm1_map_nsp="$map_dir/Nsp_map_slm1_2007-01-02.txt";
my $other_map_nsp="";	 

my $decode_map_sty="$map_dir/Sty_map_decode_2007-01-02.txt";		# 250K Sty
my $marshf_map_sty="$map_dir/Sty_map_marshf_2007-01-02.txt";
my $slm1_map_sty="$map_dir/Sty_map_slm1_2007-01-02.txt";
my $other_map_sty="";	 

my $decode_map_illumi="$map_dir/LinkageIV_map_decode_2005-02-21.txt";	# Illumina 
my $marshf_map_illumi="";
my $slm1_map_illumi="";
my $other_map_illumi="";

my $noposfile="";
my @koord=();					# all the genetic map data
my @xlist=();
my @autolist=();
my @nokoordlist=();
my %nopos=();
my %markerhash=();				# all marker names
my %alias=();
my $aliasname="SNP_A-ID";		# alias rs-number
my @autoarray=();
my $genmap="DeCode";			# default map
my $mapfunc="Haldane";			# default map function

#------ Allele Frequencies -----#
my %freqA=();
my %freqB=();

my $freq_afam_131="$map_dir/Xba131_freqA_afam.txt";		# AfroAmericans
my $freq_asian_131="$map_dir/Xba131_freqA_asian.txt";	# Asians
my $freq_cauc_131="$map_dir/Xba131_freqA_cauc.txt";		# Caucasians
my $freq_other_131="";	# Frequencies Other, my own file

my $freq_afam_142="$map_dir/Xba142_freqA_afam.txt";		# AfroAmericans
my $freq_asian_142="$map_dir/Xba142_freqA_asian.txt";	# Asians
my $freq_cauc_142="$map_dir/Xba142_freqA_cauc.txt";		# Caucasians
my $freq_other_142="";	# Frequencies Other, my own file

my $freq_afam_240="$map_dir/Xba240_freqA_afam.txt";		# AfroAmericans
my $freq_asian_240="$map_dir/Xba240_freqA_asian.txt";	# Asians
my $freq_cauc_240="$map_dir/Xba240_freqA_cauc.txt";		# Caucasians
my $freq_other_240="";	# Frequencies Other, my own file

my $freq_afam_hind="$map_dir/Hind240_freqA_afam.txt";		# AfroAmericans
my $freq_asian_hind="$map_dir/Hind240_freqA_asian.txt";	# Asians
my $freq_cauc_hind="$map_dir/Hind240_freqA_cauc.txt";		# Caucasians
my $freq_other_hind="";	# Frequencies Other, my own file

my $freq_afam_nsp="$map_dir/Nsp_freqA_afam.txt";		# AfroAmericans
my $freq_asian_nsp="$map_dir/Nsp_freqA_asian.txt";	# Asians
my $freq_cauc_nsp="$map_dir/Nsp_freqA_cauc.txt";		# Caucasians
my $freq_other_nsp="";	# Frequencies Other, my own file

my $freq_afam_sty="$map_dir/Sty_freqA_afam.txt";		# AfroAmericans
my $freq_asian_sty="$map_dir/Sty_freqA_asian.txt";	# Asians
my $freq_cauc_sty="$map_dir/Sty_freqA_cauc.txt";		# Caucasians
my $freq_other_sty="";	# Frequencies Other, my own file

my $freq_afam_illumi="$map_dir/LinkageIV_freq_afam.txt";		# AfroAmericans
my $freq_asian_illumi="$map_dir/LinkageIV_freq_asian.txt";	# Asians
my $freq_cauc_illumi="$map_dir/LinkageIV_freq_cauc.txt";		# Caucasians
my $freq_other_illumi="";	# Frequencies Other, my own file


my $allfreq="Caucasian";					# default allele frequency

#------------  GRR  ------------#
my $grrfile="grr_pedfile.dat";	# Infile for Graphical Relationship Representation
my $minbases=200000;
my $minfreq=0.10;
my $simgrr=0;

#------ Marker Selection  ------#
my $select_dist=0;
my $msminbases=100000;
my $msminfreq=0.15;
my $select_pos=0;
my $mschrom="";
my $firstmspos=0;
my $lastmspos=300000000;
my $status_markerlist=0;
my @markerlist=();		# list of markers

#------  Plot PedCheckErr  -----#
my $snperrfile="snp_err.out";
my $c_err=0;
my $c_inc=0;
my $c_snperr=0;
my $c_snp_err=0;
my $posi=0;
my %c_snp=();	# SNPs 
my %err=();				# Hash Errors err{family}{SNP}
my %hashpos=();
my %hashchr=();
my @errorlist=();		# SNP list with mendelian error
my $chrfile="chr_line\.plt";
my $valuesfile="counts.plt";
my $snpaffhet="heterozyg\.plt";
my $plotfile="myplot.gp";

#--------  Show Hetero  --------#
my @hetlist=();

#----- Make Linkage Files  -----#
my $chr_dir="";
my $targetdir="merlin";
my $gh_batch="gh_start.sh";	# Unix batchfile to start Genehunter
my $dos_batch="gh_start.bat";	# DOS batchfile to start Genehunter
my $mega2swlod="mega2sw_lod_start.sh";	# UNIX batchfile to convert mega2 to simwalk2-LOD format
my $maxsnp=300;				# maximal number of markers in pedfile for Linkage-analysis (GH2)
my @mapout=();
my (@ghunix, @swunix, @ghdos);	# arrays
my $all_markers=0;			# counts all markers used in linkage analysis
my ($marker, $value);
my %genotyp=();
my $nr=0;
my $vnr=0;					# Number of subset on a chromosome
my $lastchrom="00";			# for MakeNoLimitFiles and MakeSubsetFiles
my $selection="";			# Linkage program (to convert files)
my $subsets=0;				# 1- Subsets, 0-
my $fp=0.9999;				# disease locus wildtype frequency
my $fq=0.0001;				# disease locus mutant freqency
my $pvf1="0.000";			# penetrances
my $pvf2="0.000";
my $pvf3="1.000";
my $pvf4="1.000";			# for Imprinting model only
my $merlin_all_trait="withTrait";	# for option Merlin - All in One (with or w/o trait)

##------  Genehunter Options -----------##
# Checkbox: 0-off, 1-on
my $gh_ps1=0;	# Postscript for Family Haplotypes
my $gh_ps2=1;	# Postscript for Total stat het output
my $gh_sp=0;	# Single point
my $gh_haplo=0;	# Haplotyping 
my $gh_cr=0;	# count recs
my $gh_dis=0;	# discard 
my $gh_displ=1;	# display scores (family)
my $gh_tsh=1;	# total stat het
my $gh_tdt=0;	# TDT
my $gh_tdt2=0;	# TDT2
my $gh_mb=19;	# max bits
my $gh_step=2;	# increment step
my $gh_prog="gh";	# Genehunter executable: gh | ghm | ghi | gh2, ...
my $gh_imp=0;	# GH-Imprinting (Konstantin Strauch)
my $gh_mod=0;	# GH-Modscore (Konstantin Strauch)
my $gh_score="all";	# score function: all | pairs | hom
my $gh_offend="";	# off end xx (cM if > 0.5)


#---------  Statistics  --------#
my @allhomozygote=();
my %allhomoz=();
my $statfile="callrate.out";

#--- Calc Allele frequencies ---#
my $frqfile="alleles.frq";
my $sample_set="all founders";
my @affnonfounder=();
my @unaffounder=();


#--------- Command line --------#
my $command_line=0;
my $clhelp=0;
my $batch_file="alohomora.bch";
my @alohomora_batch=();
my @alog=();
my ($mw,$f2,$f3,$f4,$menubar,$tb);

#------------  Others  ---------#

my $work_dir=cwd();
my $datum = scalar localtime;

my $operating_system = $^O;
my $terminal='windows';
print "ALOHOMORA $version\n";
print "Operating system: $operating_system\n";
if ($operating_system =~ /solaris|linux/) {		# insert other operating systems here
    $terminal='x11';
}


if (-f "$saveenv"){ &LoadEnv;}		# if exists alohomora.ini, load
&GetArguments;
if ($clhelp == 1) { &CommandLineHelp; exit(0); }

if ($command_line == 1) {
	if (-f "$batch_file") {
		print "Read batch file : $batch_file\n";
		ShowOutput("Read batch file : $batch_file\n");
		open (IN, "$batch_file") || die "could not open $batch_file :$!\n";
		while (<IN>){
			next if /^$/;
			next if /^#/;
			chomp();
			push (@alohomora_batch,$_);
		}
		close (IN);
		
		foreach (@alohomora_batch) {
			my $command="$_";
			print "\"$command\"\n";
			eval $command;
		}
		print "Alohomora batch done\n\n";
	}
	else {
		print "No Alohomora batch\n\n";
		&SaveCurrEnv;
		$del_errors=0;
		&ReadInfiles;
		&CompareSampleIDs;
		&CheckGender;
		&PrintGRRFile;
		&PedCheck;
		&PlotPedCheckErr;
		$del_errors=1;
		&Merlin;
		system("merlin_start.pl");	### UNIX
#		system("merlin_start");	### DOS batch
		&CreMerlinErrList;
		$del_unlikely=1;
		&Allegro;
	}
}
else {

############################   M A I N  W I N D O W   ##########################

$mw = MainWindow->new(-title=>"Alohomora $version    SNP Array Quality Control and Data Conversion" );
$menubar = $mw->Frame(-relief=> "raised", -borderwidth	=> 2)
			->pack(	-anchor	=> "nw", -fill => "x");
$f2 = $mw->Frame->pack(-side=>'left',-fill=>'both');
$f3 = $mw->Frame->pack(-side=>'right',-fill=>'both');
$f4 = $mw->Frame->pack(-side=>'top',-fill=>'x');

##============================  M E N U E B A R  =============================##

my $file_menu = $menubar->Menubutton(	-text => "File", -underline => 1, -menuitems => [
						[ Button => "Open",-command => sub{$infile=FileDialog()}],
						[ Button => "Print",-command => sub {Drucken($outfile);} ],
						[ Button => "Save",-command => \&Savefile  ] ])
						->pack	(-side		=>"left" );
$file_menu->separator();
$file_menu->command(-label		=> "Quit", -command 	=> sub {Quit()});

$file_menu = $menubar->Menubutton(	-text => "Check", -menuitems => [
						[ Button => "Compare sampleIDs",-command => sub {CompareSampleIDs()}],
						[ Button => "Check gender",-command => sub {CheckGender()}],
						[ Button => "Create GRR file",-command => sub {PrintGRRFile()}],
						[ Button => "PedCheck",-command => sub {PedCheck()}]])
						->pack	(-side		=>"left" );

$file_menu = $menubar->Menubutton(	-text => "DataConversion", -menuitems => [
						[ Button => "Allegro",-command => sub {Allegro()}],
						[ Button => "Fbat",-command => sub {Fbat()}],
						[ Button => "Genehunter",-command => sub {Genehunter()}],
						[ Button => "Haploview",-command => sub {Haploview()}],
						[ Button => "Mega2",-command => sub {Mega2()}],
						[ Button => "Merlin",-command => sub {Merlin()}],
						[ Button => "Merlin - All in One",-command => sub {MW10MerlinTrait()}],
						[ Button => "Plink",-command => sub {Plink()}],					
						])
						->pack	(-side		=>"left" );

$file_menu = $menubar->Menubutton(	-text => "Options", -menuitems => [
						[ Button => "Alias names",-command => sub {MW9Alias()}],
						[ Button => "File selection",-command => sub {FileSelection()}],
						[ Button => "Select markers for GRR",-command => sub {MW7GRRFile()}],
						[ Button => "Select markers for linkage analysis",-command => sub {MW8SNPSelect()}],
						[ Button => "Phenotype selection",-command => sub {MW6PhenoSelection()}],
						[ Button => "Map function",-command => sub {MW4MapFunction()}]])
						->pack	(-side		=>"left" );

$file_menu = $menubar->Menubutton(	-text => "Plot", -menuitems => [
						[ Button => "Plot PedCheckErrors",-command => sub {PlotPedCheckErr()}]])
#						[ Button => "Plot SNPfile",-command => sub {PlotFile()}]])
						->pack	(-side		=>"left" );

$file_menu = $menubar->Menubutton(	-text => "Utilities", -menuitems => [
						[ Button => "Calculate allele frequencies, callrate, HWE",-command => sub {MW11CalcAllFreq()}],
						[ Button => "Calling rate",-command => sub {CallingRate()}],
						[ Button => "Create Merlin unlikely list",-command => sub {CreMerlinErrList()}],
						[ Button => "Delete errors in families",-command => sub {DelErrors()}],
						[ Button => "PedStat",-command => sub {MW5PedStat()}],
						[ Button => "Save current environment",-command => sub {SaveCurrEnv()}]])
						->pack	(-side		=>"left" );
$file_menu = $menubar->Menubutton(	-text => "Help", -menuitems => [
						[ Button => "Show Help",-command => sub {ShowHelp()}],
						[ Button => "About",-command => sub {About()}]])
						->pack	(-side		=>"left" );


##===============================  F R A M E  2  =============================##

$f2->Label(-text => "Chip",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'w');

my $be2f2=$f2->BrowseEntry( -width=>10, -listwidth=>20, -variable => \$chip);
foreach (qw(Xba131 Xba142 Xba240 Hind240 Nsp Sty Illumina)) { $be2f2->insert("end","$_");}
$be2f2->pack(-side => 'top',-anchor =>'nw');


#----------------#
$f2->Label(-text => "Filter markers",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'w');

my $cb1_f2=$f2->Checkbutton(-text 	=> "w/o position",
						-variable => \$skip_nopos)-> pack(-side => 'top',-anchor =>'nw');
my $cb2_f2=$f2->Checkbutton(-text 	=> "skip ME",
						-variable => \$skip_errors)-> pack(-side => 'top',-anchor =>'nw');
my $cb5_f2=$f2->Checkbutton(-text 	=> "skiplist",
						-variable => \$skip_list)-> pack(-side => 'top',-anchor =>'nw');
my $cb3_f2=$f2->Checkbutton(-text 	=> "skip non-informative",
						-variable => \$skip_notinf)-> pack(-side => 'top',-anchor =>'nw');

$f2->Label(-text => "Filter genotypes",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'w');

my $cb6_f2=$f2->Checkbutton(-text 	=> "delete ME",
						-variable => \$del_errors)-> pack(-side => 'top',-anchor =>'nw');
my $cb4_f2=$f2->Checkbutton(-text 	=> "delete unlikely genotypes",
						-variable => \$del_unlikely)-> pack(-side => 'top',-anchor =>'nw');

#-------------##
$f2->Label(-text => "Genetic map",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'w');
# Radiobuttons erzeugen
foreach (qw(DeCode Marshf SLM1 Other)) {
	my $rb2_f2=$f2->Radiobutton(-text 	=> $_,
		-value 	=> $_,
		-variable => \$genmap)-> pack(-side => 'top',-anchor =>'nw');
}


#-------------##
$f2->Label(-text => "Allele frequencies",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'w');
# Radiobuttons erzeugen
foreach (qw(AfAm Asian Caucasian Other equal)) {
	my $rb3_f2=$f2->Radiobutton(-text 	=> $_,
		-value 	=> $_,
		-variable => \$allfreq)-> pack(-side => 'top',-anchor =>'nw');
}

#-------------##
$f2->Label(-text => "Plot",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'w');

my $be1_f2=$f2->BrowseEntry(-label =>"Chr\n" ,	-width=>5, -listwidth=>20, -variable => \$pchrom);
$be1_f2->insert("end","ALL");

foreach my $i ('01','02','03','04','05','06','07','08','09',10,11,12,13,14,15,16,17,18,19,20,21,22,23) {
	$be1_f2->insert("end","$i");
}
$be1_f2->pack(-side => 'top',-anchor =>'nw');

##==============================  F R A M E  4  ==============================##
my $b1_f4 = $f4->Button(-text => "Genotypefile",
					-command=>sub{$infile=FileDialog("Select GDAS genotype file")})->pack(-side => 'left');
my $e1_f4 = $f4->Entry(-textvariable => \$infile,
					-width=> '30')->pack(-side =>'left');


my $b2_f4= $f4->Button(-text => "Read Infiles",
					-command=>sub{&ReadInfiles})	->pack(-side => 'left',-fill=>'x');
my $b3_f4= $f4->Button(-text => "PedCheck",
					-command=>sub{PedCheck()})	->pack(-side => 'left',-fill=>'x');
my $b6_f4= $f4->Button(-text => "GRR",
					-command=>sub{PrintGRRFile()})	->pack(-side => 'left',-fill=>'x');
my $b7_f4= $f4->Button(-text => "Clear",
					-command=>sub{ClearWindow()})	->pack(-side => 'left',-fill=>'x');
my $b_ende_f4= $f4->Button(-text => "Quit",
					-command=>sub{Quit()})->pack(-side => 'left',-fill=>'x');

##==============================  T E X T   B O X  ===========================##

$tb=$mw->Scrolled("Text",-width=>90, -height=>43, -scrollbars => 'e')->pack(-side=>'bottom',-fill=>'both');


MainLoop();

}

################################################################################
##################################  S U B s   ##################################
################################################################################
sub ReadInfiles {
	ShowOutput("ALOHOMORA $version\n");
	ShowOutput("Date: $datum\nPath: $work_dir\n");
	if ($infile eq "") {$infile=FileDialog("select genotype file");}
	$dirname=dirname($infile);
	if (($work_dir ne $dirname) && ($dirname ne "\.")) {
		print "change working directory to $dirname\n";
		if (chdir "$dirname") {
			ShowOutput("working directory changed to $dirname\n");
			$work_dir=$dirname;
		}
		else {ShowOutput("can not change working directory to $dirname\n");}
	}
	
	&ReadGenMap;
	&ReadAllFreq;
	&ReadSkipList;
	&ReadGenotypeFile;
	&ReadPedfilePro;
	&ReadQTLfile;
	&MakeHashGtypes;
	print "\nRead InFiles done\n\n";
	ShowOutput("\nRead infiles done\n\n");
	
}

###########################   S K I P    L I S T  ############################

sub ReadSkipList {
	@skipextra=();
	if ($skip_list == 1) { # Skip SNPs from extra skiplist (e.g. SNPs not in HWE, bad CallRate)
		$nr=0;
		if (-f $skipfile) {
			open (IN, "$skipfile") || die "could not open $skipfile :$!\n";
			print "Read skiplist     : $skipfile\n";
			ShowOutput ("\nRead skiplist : $skipfile");
			while (<IN>){
				next if /^$/;
				next if /^#/;
				chomp;
				my @row=split(' ',$_);
				push (@skipextra,$row[0]); $nr++;	# create array SNPs to skip
			}
			close (IN);
			ShowOutput("\t$nr SNPs\n");
			$status_skiplist=1;
		}
		else {
			print "not found skiplist : $skipfile\n";
			ShowOutput("not found skiplist : $skipfile\n");
		}
	}
	else {
		print "skiplist not selected\n";
		ShowOutput ("\nSkiplist not selected\n");
	}
}


###########################  R E A D  I N F I L E   ############################

sub ReadGenotypeFile {
	my $c1=0;	# all SNP-lines in infile
	my $c2=0;	# SNPs not skipped
	my $c_gmap=0;	# count unmatched SNP names in genetic map
	my $c_freq=0;	# count unmatched SNP names in allele freq file
	@data=();	# initialize dataarray
	@skip=();	# initialize skiplist
	%skiplist=();	# Hash (key is SNP-name)
	%samples=();	# hash, key is sampleID

	if ($skip_nopos == 1) {push (@skip,@nokoordlist);}	# Skip SNPs without position
	if ($skip_list == 1) {push (@skip,@skipextra);}	# Skip SNPs in extra skip_list
	if ($skip_errors == 1) {&ReadPedCheckErr;  push(@skip,@errorlist);}	# Skip SNPs with errors
	foreach my $snp (@skip) {	# Creates hash from skiplist
		$skiplist{$snp}=1;
#		print "$snp\n";
	}

	$basename=basename($infile);
	my @v = split('\.',$basename) ;
	$base_no_ext="$v[0]";		# Genotype filename without extension

	if (! -f $infile) { 	ShowOutput("\nnot found : $infile\n"); return;}

	print "Read genotypefile\t: $infile\n";
	ShowOutput("\nRead genotypefile : $infile\n");
	open (IN, "$infile") || die "could not open genotypefile $infile :$!\n";
LINE1: while (<IN>){
		next LINE1 if /^$/;
		chomp;
		if ($. == 1) {
			$header=$_;
			@head=split('\t',$_);
			for (my $z=1;$z<=$#head;$z++) {	# parse header line
				$head[$z] =~ s/_Call$//i;
				my @feld=split($FS,$head[$z]);
				if ($#feld > 1) {$sample{$z}=$feld[2];$samples{$feld[2]}++;}  ### SampleID in 3th field
				else {$sample{$z}=$feld[0]; $samples{$feld[0]}++;}	# Hash SampleID in Spalte $z #
			}
		}
		else {
			$c1++;
			s/NoCall/NC/g;
			s/--/NC/g;
#			s/TSC/tsc/g;
			my @row=split('\t',$_);
			##### if TSC-number has no leading zeros - convert #####
#			if ($row[0] =~ /^SNP|^rs/) { ;}
#			elsif ($row[0] =~ /tsc/) {
#				if (length($row[0]) == 9) { $row[0] =~ s/tsc/tsc0/; s/tsc/tsc0/;}
#				elsif (length($row[0]) == 8) { $row[0] =~ s/tsc/tsc00/; s/tsc/tsc00/;}
#				elsif (length($row[0]) == 7) { $row[0] =~ s/tsc/tsc000/; s/tsc/tsc000/;}
#				elsif (length($row[0]) == 6) { $row[0] =~ s/tsc/tsc0000/; s/tsc/tsc0000/;}
#				elsif (length($row[0]) == 5) { $row[0] =~ s/tsc/tsc00000/; s/tsc/tsc00000/;}
#				else { ;}
#			}
#			else {
#				if (length($row[0]) == 7) { $row[0] = "tsc"."$row[0]";}
#				elsif (length($row[0]) == 6) { $row[0] = "tsc0"."$row[0]";}
#				elsif (length($row[0]) == 5) { $row[0] = "tsc00"."$row[0]";}
#				elsif (length($row[0]) == 4) { $row[0] = "tsc000"."$row[0]";}
#				elsif (length($row[0]) == 3) { $row[0] = "tsc0000"."$row[0]";}
#				else {;}			
#			}

			if ($skiplist{$row[0]}) {next LINE1;}	# don't read in this SNPs
			push (@data,$_);	# data of (infile - skiplist)
			$c2++;
			if ( ! $markerhash{$row[0]}) {$c_gmap++;}
			if ( ! $freqA{$row[0]}) {$c_freq++;}
		}
	}
	close (IN);

	print "\tRead  $#head samples";
#	for ($i=1; $i<=$#head;$i++) {
#		print " \"$sample{$i}\"";
#	}
	print "\n\n";

	my $c3=$c1-$c2;
	ShowOutput("\t$#head samples; $c2 of $c1 SNPs read in, $c3 skipped\n");
	$statusdata=1;
	if ($c_gmap > 0 ) { ShowOutput("\n\t$c_gmap SNPs have no entry in genetic map file\n");}
	if ($c_freq > 0 ) { ShowOutput("\t$c_freq SNPs have no entry in allele frequency file\n");}
	
}


########################  M A K E   H A S H   G E N O T Y P E S    #################
sub MakeHashGtypes {
	print "MakeHashGtypes ...\n";
	ShowOutput("\nMake Hash Gtypes ...\n");
	
	@names=();
	%gtype=();
	%gnames=();
	my $var=($#head * ($#data+1));
	keys (%gtype)=($var);
	keys (%gnames)=($#data+1);
	foreach (@data) {	# fr jeden SNP
		my @v=split('\t',$_);
		push (@names,$v[0]);
		$gnames{$v[0]}=1;
		for (my $z=1;$z<=$#head;$z++) 	{	# fr jede Person
			$gtype{$sample{$z}}{$v[0]} = $v[$z];
		}
	}
}


######################  R E A D   P E D F I L E  P R O  ########################

sub ReadPedfilePro {  ## noch zu berarbeiten
	if ( ! -f $pedfilepro ){
		ShowOutput("Pedfile.pro not found $pedfilepro !\n");
		if ($command_line == 0) { Errormsg("Pedfile.pro not found $pedfilepro !\nPedCheck not possible!"); }
		return($pedfilepro);
  	}

  	%famlist=();
  	%gender=();
  	%indiv=();
  	@pedcheck=();
  	@pedfile=();
  	@fam=();
  	@ind=();
  	@affind=();
  	@founder=();
	@affnonfounder=();
	@unaffounder=();
  	$count=0;
	open (fhin, "$pedfilepro") || die "could not open pedfile $pedfilepro :$!\n";
  	print "Read Pedfile       :$pedfilepro\n";
	ShowOutput("\nRead pedfile      : $pedfilepro\n");
		
	while (<fhin>){
		next if /^$/;
		next if /^\*/;
		next if /^\#/;
		chomp ();
#		s/\./-/g;	# genehunter accepts "-" in sampleID
		my @p=split(' ',$_);
		if ($#p < 4) {next;}	# Zuwenig Felder fr Pedfile
		if ($p[1] eq "") {next;}	# empty PID
		$count++;
		my ($fam,$ind,$dad,$mom,$sex,$aff,$liab,@rest) = @p;
		if ($aff eq "2") { push(@affind,$ind);}	# array - list of affected ind
		if ($dad eq "0") { push(@founder,$ind);}	# array - list of founders
		if (($aff == 1) && ($dad eq "0")) { push(@unaffounder,$ind);}	# array - affected non-founder 
		if (($aff == 2) && ($dad ne "0")) { push(@affnonfounder,$ind);}	# array - affected non-founder 

		$gender{$ind}=$sex;	# Gender of individual = key
		$indiv{$ind}++;		# count sample IDs
		$famlist{$fam}++;	# Hash family name = key
		$fam[$count]=$fam;
		$ind[$count]=$ind;	# Individual in Line
		$pedcheck[$count]="$fam $ind $dad $mom $sex "; # Pedigree structure for PedCheck
		$pedfile[$count]="$fam $ind $dad $mom $sex $aff "; # Pedigree structure for Linkage w/o liability classes
	
		push (@{$member{$fam}},$ind);
	}
	close (fhin);
	print "\taffected:";
	foreach (@affind) {print " $_";}
	print "\n\n";
#	foreach $fam (keys %member){
#		print "$fam: @{$member{$fam}}\n";
#	}
	my $ci=(keys %indiv);
	my $cf=(keys %famlist);
	my $i=0;		# number of samples shared by genotype file and pedfile.pro
	foreach (keys %samples){if (exists $indiv{$_}) {$i++;}}
	ShowOutput("\t$cf families, $ci individuals\n");
	ShowOutput("\t$i samples shared with genotype file\n");
	
	$statusped=1;
} ## end ReadPedfilePro

########################  R E A D   Q T L F I L E     ##########################
sub ReadQTLfile {
	if ($qtl_select == 0) {return;}
	
	%qtlname=();
	my %qtlcount=();		# hash - number of traits for each individual
	
	if ( ! -f $qtlfile ){
		Errormsg("QTLfile not found $qtlfile !\n");
		ShowOutput("\nQuantitative trait file $qtlfile not found\n\n");
		return;
  	}

	my $anz_qtllines=0;
	my %qtlpers=();
	%qtltraits=();
	
  	open (IN, "$qtlfile") || die "could not open qtlfile $qtlfile :$!\n";
	ShowOutput("\nRead QTL file     : $qtlfile\n");
	while (<IN>){
		next if /^$/;
		next if /^\*/;
		if (($. ==1) && ($_ =~/^\#/)){
			chomp ();
			my @v=split(' ',$_);
			$c_traits=$#v;
			for (my $i=1;$i<=$#v;$i++){
				$qtlname{$i}=$v[$i];
			}
		}
		else {
			next if /^\#/;	
			chomp ();
			my @v=split(' ',$_);
			$qtltraits{$v[0]}=$_;	# Inhalt zeile im qtl file, key ist sampleID
			$qtlpers{$v[0]}++;		# wie hufig kommt sampleID vor, key ist sampleID
			$qtlcount{$v[0]}=$#v;	# Anzahl traits fr sample, key ist sampleID
			$anz_qtllines++;		# Zeilen im qtl file
		}
	}
	close (IN);
	
	### ---- Check QTL file ---- ###
	my $c=0;
	my %c_hash=();		

	foreach my $key (keys %qtlpers){	# Are there doubled sampleIDs?
		$c++;
		if ($qtlpers{$key} > 1) { print "sample $key is $qtlpers{$key} times in qtl file\n";}
	}

	foreach my $key (keys %qtlcount){	# Haben alle samples die gleiche Anzahl traits?
		$c_hash{$qtlcount{$key}}++;
	}
		
	print "\nShow c_hash\n";

	ShowOutput("\t$anz_qtllines lines in file have ${c} different sampleIDs\n");
	foreach my $key (keys %c_hash){ 
		ShowOutput("\t$c_hash{$key} samples have $key traits each\n");
		print "$key\t$c_hash{$key}\n";
	}
	$qtl_status=1;
}

##############################   P E D C H E C K   #############################
sub PedCheck {
    if ($statusdata == 0) {
    	Errormsg("No data loaded!\nPlease enter genotypefile and read files!\n");
		ShowOutput("\nNo data loaded!\n"); return;  
	}
  	ShowOutput("\nStart PedCheck \n");

	%snphet=();	# SNP is heterozygote at affected ind

	if ($del_errors == 1) {&DelErrors;}

	if ( -f $pedcheckall) { 
		my $outfile="${pedcheckall}0";
		print "Save old $pedcheckall to $outfile\n\n";
 	 	ShowOutput("Save old $pedcheckall to $outfile\n");
		copy ($pedcheckall,$outfile);
	}

    if ($statusmap == 0){ &ReadGenMap;}
    if ($statusped == 0) {&ReadPedfilePro;}

	print "Sub PrintPedcheckFile Pedfile: $pedcheckfile  Names: $namesfile  \n";
	print "Linked: $linked\tMaxmarker: $maxmarker\n\n";
   system "echo $datum > $pedcheckall";

	$linked = 'autosomal';
#	$maxmarker=1000;
    @snplist=@autolist;
    if ($skip_nopos == 0) {push (@snplist,@nokoordlist);}
    &PrepPedCheck;

	$linked = 'X-linked';
	@snplist=@xlist;
	&PrepPedCheck;

	$linked = 'both';

  	&CleanFiles;
  	ShowOutput("\nPedCheck done\n");
  	print "\nPedCheck done\n";
   
}

###########################  P R E P  P E D C H E C K  #########################
sub PrepPedCheck {
	my $k;
	for (my $anz=0;$anz<$#snplist;$anz+=$maxmarker) {# Pedcheck mit jeweils maxmarker SNPs aufrufen
		my $var=$anz+$maxmarker;
		if ($var > $#snplist) {$var=$#snplist + 1;}
#		my $anz1=$anz+1;
		my $var1=$var-1;
		print "Subset: $anz - $var1\n";
  		ShowOutput(" .");

		open (fhout,"> $pedcheckfile") || die "could not open $pedcheckfile :$!\n";
		open (fh_names,"> $namesfile") || die "could not open $namesfile :$!\n";
PEDI:	for (my $i=1;$i<=$count;$i++) {	# for each
			print fhout "$pedcheck[$i] ";
			for ($k=$anz;$k<$var;$k++) {
#				if ($k > $#snplist){ print fhout "\n";next PEDI;}
				if ($i==1) { print fh_names "$snplist[$k]\n";}
				if (! exists $gtype{$ind[$i]}{$snplist[$k]}) { # No Hash if not genotyped
					print fhout " 0 0";
				}
				else {	# if genotyped then recode the Hash value and print
					if 	  (($gtype{$ind[$i]}{$snplist[$k]} eq "AA")||($gtype{$ind[$i]}{$snplist[$k]} eq "A")) {print fhout " 1 1";}
					elsif (($gtype{$ind[$i]}{$snplist[$k]} eq "BB")||($gtype{$ind[$i]}{$snplist[$k]} eq "B")){print fhout " 2 2";}
					elsif ($gtype{$ind[$i]}{$snplist[$k]} eq "AB") {print fhout " 1 2";}
					elsif ($gtype{$ind[$i]}{$snplist[$k]} eq "NC"){print fhout " 0 0";}
					else {print fhout " X X";}
				}
			}
			print fhout "\n";
		}
		close (fhout);
		close (fh_names);
		&StartPedcheck;
		&CountGtypdpers;
		system "echo Marker number: $anz \- $k >> $pedcheckall\n"; # output of all PedCheck results
		my $command="cat pedcheck.err >> $pedcheckall";		### UNIX
#		my $command="type pedcheck.err >> $pedcheckall";	### DOS
		system "$command";

		if (! -d "pedfiles") {mkdir ("pedfiles",0777);}
		my $newfile="$pedcheckfile"."$var";
		copy ($pedcheckfile, "pedfiles/$newfile");
		$newfile="$namesfile"."$var";
		copy ($namesfile,"pedfiles/$newfile");
  	}
}

#########################   S T A R T   P E D C H E C K    ###########################
sub StartPedcheck {
	my $command="";
	
	if ($linked eq 'autosomal') {
		print "\n Start PedCheck with autosomal data, please wait ...\n";
		$command="pedcheck -2 -p $pedcheckfile -n $namesfile > /dev/null";	### UNIX
#		$command="pedcheck -2 -p $pedcheckfile -n $namesfile > nul";	### DOS
	}
	else {
		print "\n Start PedCheck with x-linked data, please wait ...\n";
		$command="pedcheck -x -2 -p $pedcheckfile -n $namesfile > /dev/null";	### UNIX
#		$command="pedcheck -x -2 -p $pedcheckfile -n $namesfile > nul";	### DOS
	}
	system "$command";				# starts PedCheck
}


##########################  Count genotyped individuals  #############################
sub CountGtypdpers { ## Control of PedCheck "pedfile.dat", are there genotyped individuals?

	open (fhin," $pedcheckfile") || die "$pedcheckfile konnte nicht gelesen werden.\n";
	my $gtypd_persons=0;
	LINE: while (<fhin>){
		chop();
		my @feld = split(' ',$_);
		for (my $i=5;$i<=$#feld;$i++) {
			if ($feld[$i] ne 0) {$gtypd_persons++;next LINE;}
		}
	}
	close (fhin);
	print " $gtypd_persons genotyped individuals were checked\n\n"
}

##################  I N I T I A L I Z E  S K I P L I S T  ######################
sub InitializeSkiplist {

	my @skip=();	# collect markernames
	%skiplist=();	# Hash skiplist (key is SNP-name)

	### no position
	if ($skip_nopos == 1) {push (@skip,@nokoordlist);}	# Skip SNPs without position

	### skiplist from file
	if ($skip_list == 1) {
		if ($status_skiplist == 0) { &ReadSkipList; }
		push (@skip,@skipextra);}	# Skip SNPs in extra skip_list

	### Mendelian errors
	if ($skip_errors == 1) {
		if ($status_PedCheckErr == 0) { &ReadPedCheckErr;}
		push(@skip,@errorlist);	# Skip SNPs with errors
	}

	### non-informative markers
	if ($skip_notinf == 1) {	# Skip non-informative SNPs
		if ($statusstat == 0) { &CallingRate; }	
		push (@skip,@allhomozygote);
	}

	### create hash skiplist
	foreach (@skip) {	# Creates hash from skiplist
		$skiplist{$_}=1;
	}

}

##########################  Plot File  ##########################

sub PlotFile {

	&ReadPlotFile;
	if ($statusmap  == 0) {&ReadGenMap;}

	if ($pchrom eq "ALL") {
		&MakeGraficsAll;
	}
	else {
		&MakeGraficsOne;
	}

	system ("gnuplot $plotfile");
	
	&CleanFiles;

}

##########################  Read File  ##########################

sub ReadPlotFile {
	ShowOutput("Read SNPlistfile : $infile\n");
	open (IN, "$infile") || die "could not open $infile :$!\n";
	%c_snp=();
	while (<IN>){
		next if /^$/;
		next if /^#/;
		next if /^SNP/;
		chomp();
		my @row = split('\t',$_);
		$c_snp{$row[0]}++;	# SNP-liste in erster Spalte
	}
	close (IN);
}


##########################  Plot PedCheck Errors  ##########################

sub PlotPedCheckErr {
	if ($statusped == 0) {&ReadPedfilePro;}
	if ($statusmap  == 0) {&ReadGenMap;}
	&ReadPedCheckErr;
	
	print "Sub PlotPedCheckErr Option: $pchrom\n";
	if ($pchrom eq "ALL") {
		&MakeGraficsAll;
		&PrintErrList;
	}
	else {
		&MakeGraficsOne;
	}
	system ("gnuplot $plotfile");
	ShowOutput("\n$c_snp_err SNPs have $c_err errors\n");
	ShowOutput("PlotPedCheckErr done\n");
	
	&CleanFiles;
#	return (my $back);
}

##########################  Read ALL PedCheck Errors  ##########################

sub ReadPedCheckErr {
    %c_snp=();	# Hash: value - How many times has a SNP an error, key - SNPname
    my $lic="";	# license expired line
    $c_err=0;	# Sum of all errors
    $c_inc=0;	# Sum of all inconsistencies  (incl. multiple errors in one family)
    @errorlist=();	# SNP-list with mendel errors
    %err=();
    my $fam="";
    my $snp="";

    if ( ! -f $pedcheckall) {print "$pedcheckall not found\n";return;}
	open (IN, "$pedcheckall") || die "could not open $pedcheckall :$!\n";
	print "\nRead PedCheck errorfile\n";
	ShowOutput("\nRead PedCheck errorfile:");
	
 	while (<IN>){
 		next if /^$/;
    	chomp();
    	my @row = split(' ',$_);
    	if ( $row[8] eq "expired") { $lic=$_;}
		if (($row[0] eq "!") && ($row[1] eq "marker")) {$c_snp{$row[2]}++;$c_err++;}
		if ($row[4] eq "inconsistencies") { $c_inc += $row[3];}	#print "$_\n";
		if ($_ =~ /^\#\#\#\#\# GENOTYPE ERROR/) {
			$fam=$row[4]; # print "fam $fam";
			$snp=$row[8]; # print "snp $snp\n";
			$err{$fam}{$snp}++;
		}
	}
	close (IN);
	foreach (keys %c_snp) {
		push (@errorlist,$_);
	}
	$c_snp_err=$#errorlist + 1;

	if ($lic ne "") { print "$lic\n";}
	else {print "Error list : $c_snp_err SNPs\n\n";}
	if ($lic ne "") {ShowOutput("\t$lic\n");}	
	else { ShowOutput("\t$c_snp_err SNPs have errors\n");}
	$status_PedCheckErr=1;
}


#########################  R E A D  G E N E T I C  M A P   ##########################

sub ReadGenMap {	# Read genetic map
	my $c_map=0;
	@koord=();
	@xlist=();
	@autolist=();
	@nokoordlist=();
	@autoarray=();
	%markerhash=();
	%alias=();
	
	my $markermap="";

	if ($chip eq "Xba131") {
		if ($genmap eq "DeCode") {$markermap=$decode_map_131;}
		elsif ($genmap eq "Marshf") {$markermap=$marshf_map_131;}
		elsif ($genmap eq "SLM1") {$markermap=$slm1_map_131;}
		else {$markermap=$other_map_131;}		
	}
	elsif ($chip eq "Xba142") {
		if ($genmap eq "DeCode") {$markermap=$decode_map_142;}
		elsif ($genmap eq "Marshf") {$markermap=$marshf_map_142;}
		elsif ($genmap eq "SLM1") {$markermap=$slm1_map_142;}
		else {$markermap=$other_map_142;}
	}
	elsif ($chip eq "Xba240") {
		if ($genmap eq "DeCode") {$markermap=$decode_map_240;}
		elsif ($genmap eq "Marshf") {$markermap=$marshf_map_240;}
		elsif ($genmap eq "SLM1") {$markermap=$slm1_map_240;}
		else {$markermap=$other_map_240;}
	}
	elsif ($chip eq "Hind240") {
		if ($genmap eq "DeCode") {$markermap=$decode_map_hind;}
		elsif ($genmap eq "Marshf") {$markermap=$marshf_map_hind;}
		elsif ($genmap eq "SLM1") {$markermap=$slm1_map_hind;}
		else {$markermap=$other_map_hind;}
	}
	elsif ($chip eq "Nsp") {
		if ($genmap eq "DeCode") {$markermap=$decode_map_nsp;}
		elsif ($genmap eq "Marshf") {$markermap=$marshf_map_nsp;}
		elsif ($genmap eq "SLM1") {$markermap=$slm1_map_nsp;}
		else {$markermap=$other_map_nsp;}
	}
	elsif ($chip eq "Sty") {
		if ($genmap eq "DeCode") {$markermap=$decode_map_sty;}
		elsif ($genmap eq "Marshf") {$markermap=$marshf_map_sty;}
		elsif ($genmap eq "SLM1") {$markermap=$slm1_map_sty;}
		else {$markermap=$other_map_sty;}
	}
	elsif ($chip eq "Illumina") {
		if ($genmap eq "DeCode") {$markermap=$decode_map_illumi;}
		elsif ($genmap eq "Marshf") {$markermap=$marshf_map_illumi;}
		elsif ($genmap eq "SLM1") {$markermap=$slm1_map_illumi;}
		else {$markermap=$other_map_illumi;}
	}
	else {;}

	
	if ( ! -f $markermap) {
		print "Could not open markermap $markermap\n";
		ShowOutput("Could not open markermap $markermap\n");
		
		return;
	}

	print "\nRead MarkerMap       : $markermap\n";
	open (IN, "$markermap") || die "could not open markermap $markermap :$!\n";
	while (<IN>){
		next if /^$/;		# skip blank line
		next if /^#/;		# skip comment line
		next if /^\*/;		# skip comment line
		if (($.==1) && (uc($_) =~ /^CHR/)) {next;}		# skip header line, was bug in v0.32
		chomp;
		$c_map++;
		push (@koord,$_);	# all
		my @v=split('\t',$_);
		if (($v[0] eq '23') || ($v[0] eq 'X')) {push (@xlist,$v[1]);$markerhash{$v[1]}=1;}	# x-linked
		elsif ($v[0] > 0.) {push (@autolist,$v[1]);$markerhash{$v[1]}=1;push (@autoarray,$_);}
		else {push (@nokoordlist,$v[1]); $nopos{$v[1]}=1;}
		
		if ($v[4] =~ /^rs/) {$alias{$v[1]}=$v[4];}
		else {$alias{$v[1]}=$v[1];}
	}

	close (IN);
	$statusmap=1;
	ShowOutput("\nRead markermap      :\t$markermap\n\tSNPs in map :\t$c_map\n");
	print "\tSNPs in map   :\t$c_map\n";
	my $var=$#autolist+1;
	print "\tautosomal     :\t$var marker\n";
	ShowOutput("\tautosomal   :\t$var marker\n");
	$var=$#xlist+1;
	print "\tX-linked      :\t$var marker\n";
	ShowOutput("\tX-linked    :\t$var marker\n");
	$var=$#nokoordlist+1;
	print "\tno-position   :\t$var marker\n\n";
 	print "\n";
	ShowOutput("\tno-position :\t$var marker\n\n");
	
}

###################  R E A D  A L L E L E  F R E Q U E N C I E S   ####################

sub ReadAllFreq {	# Read SNP allele frequencies
	%freqA=();
	%freqB=();
	my $snp="";
	my $diff=0;
	my $fA="";
	my $fB="";
	my $sk=0;

	my $freqfile="";

	if ($chip eq "Xba131") {
		if ($allfreq eq "AfAm") {$freqfile=$freq_afam_131;}
		elsif ($allfreq eq "Asian") {$freqfile=$freq_asian_131;}
		elsif ($allfreq eq "Caucasian") {$freqfile=$freq_cauc_131;}
		elsif ($allfreq eq "Other") {$freqfile=$freq_other_131;}
		else {$freqfile = "";}
	}
	elsif ($chip eq "Xba142") {
		if ($allfreq eq "AfAm") {$freqfile=$freq_afam_142;}
		elsif ($allfreq eq "Asian") {$freqfile=$freq_asian_142;}
		elsif ($allfreq eq "Caucasian") {$freqfile=$freq_cauc_142;}
		elsif ($allfreq eq "Other") {$freqfile=$freq_other_142;}
		else {$freqfile = "";}
	}
	elsif ($chip eq "Xba240") {
		if ($allfreq eq "AfAm") {$freqfile=$freq_afam_240;}
		elsif ($allfreq eq "Asian") {$freqfile=$freq_asian_240;}
		elsif ($allfreq eq "Caucasian") {$freqfile=$freq_cauc_240;}
		elsif ($allfreq eq "Other") {$freqfile=$freq_other_240;}
		else {$freqfile = "";}
	}
	elsif ($chip eq "Hind240") {
		if ($allfreq eq "AfAm") {$freqfile=$freq_afam_hind;}
		elsif ($allfreq eq "Asian") {$freqfile=$freq_asian_hind;}
		elsif ($allfreq eq "Caucasian") {$freqfile=$freq_cauc_hind;}
		elsif ($allfreq eq "Other") {$freqfile=$freq_other_hind;}
		else {$freqfile = "";}
	}
	elsif ($chip eq "Nsp") {
		if ($allfreq eq "AfAm") {$freqfile=$freq_afam_nsp;}
		elsif ($allfreq eq "Asian") {$freqfile=$freq_asian_nsp;}
		elsif ($allfreq eq "Caucasian") {$freqfile=$freq_cauc_nsp;}
		elsif ($allfreq eq "Other") {$freqfile=$freq_other_nsp;}
		else {$freqfile = "";}
	}
	elsif ($chip eq "Sty") {
		if ($allfreq eq "AfAm") {$freqfile=$freq_afam_sty;}
		elsif ($allfreq eq "Asian") {$freqfile=$freq_asian_sty;}
		elsif ($allfreq eq "Caucasian") {$freqfile=$freq_cauc_sty;}
		elsif ($allfreq eq "Other") {$freqfile=$freq_other_sty;}
		else {$freqfile = "";}
	}
	elsif ($chip eq "Illumina") {
		if ($allfreq eq "AfAm") {$freqfile=$freq_afam_illumi;}
		elsif ($allfreq eq "Asian") {$freqfile=$freq_asian_illumi;}
		elsif ($allfreq eq "Caucasian") {$freqfile=$freq_cauc_illumi;}
		elsif ($allfreq eq "Other") {$freqfile=$freq_other_illumi;}
		else {$freqfile = "";}
	}
	else {;}	
		
	if ($freqfile eq "") {
		print "\nEqual distributed allele frequencies used\n";
		ShowOutput("\nEqual distributed allele frequencies used\n\n");
		return;
	}
	if (! open (IN, "$freqfile")){ ShowOutput("\nCould not open allele frequency file $freqfile\n");return;}
	while (<IN>){
		next if /^$/;		# skip blank line
		next if /^\#/;		# skip comment line
		next if /^\*/;		# skip comment line
		if ($. == 1) {next;}	# skip header line 	
		chomp;
		my ($snp,$fA,@v)=split(' ',$_);
		if (($fA =~ /---/) || ($fA =~ /NA/) || ($fA eq "") ) { $sk++; next;} 	# skip when no frequency available
		$fA=sprintf("%5.4f",$fA);
		if ($fA == 0) {$fA=0.0100;}
		if ($fA == 1) {$fA=0.9900;}
		$fB=sprintf("%5.4f",1-$fA);
		$freqA{$snp}=$fA;
		$freqB{$snp}=$fB;
	}
	close(IN);
	
	my $nr= (keys %freqA);
	ShowOutput("Read allele frequencies: $freqfile\n");
	ShowOutput("\t$nr SNPs read in, $sk skipped\n");
	print "Read allele frequencies: $freqfile\n";
	print "\t$nr SNPs read in, $sk skipped\n";
	$statusfreq=1;
	
}


########################  M A R K E R  S E L E C T I O N   #####################
sub MarkerSelection {
	if (($select_pos == 0) && ($select_dist == 0)) {
		$status_markerlist = 0;
		return;
	}
	
	if ($statusmap == 0){&ReadGenMap;}
	if ($statusfreq == 0) {&ReadAllFreq;}

	&InitializeSkiplist;

	ShowOutput( "\nSelect markers from genetic map for linkage analysis\n");
	my @maptmp=();
	if (length($mschrom) ==1) {$mschrom="0"."$mschrom";}
	
	if ($select_pos == 1) {
		ShowOutput( "\tchromosome: $mschrom\n\tfirst position: $firstmspos\n\tlast position: $lastmspos\n");

		foreach (@koord) {	# select SNPs from map by physical position 
			my ($chrom,$marker,$genpos,$physpos,@rest)=split('\t',$_);
			if (	exists $skiplist{$marker}) {next;}

			if (($chrom eq "$mschrom") && ($physpos > $firstmspos) && ($physpos < $lastmspos)) {
				push (@maptmp,$_);
			}
		}
	}
	else {@maptmp = @koord;}


	if ($select_dist == 1) {
		@markerlist=();	# selection of markers for linkage analysis
		my $lastchrom="XXX";
		my $nextpos= 0.;
		my $maxfreq=1-$msminfreq;

		ShowOutput( "\tmin. distance: $msminbases bases\n\tminor allele freqency: $msminfreq\n");
	
		foreach (@maptmp) {	# select SNPs from genetic map with high minor allele frequency

			my ($chrom,$marker,$genpos,$physpos,@rest)=split('\t',$_);
			if (exists $skiplist{$marker}) {next;};
			
			next if $chrom eq /'NA'|''/;
			next if $chrom =~ /---/;
			if ($chrom ne $lastchrom) {
				$lastchrom = $chrom;
				$nextpos = 0.;
			}
			if (($physpos > $nextpos) && (exists ($freqA{$marker}))) {
				if  ($freqA{$marker} > $msminfreq and $freqA{$marker} < $maxfreq) {
					push (@markerlist,$_);
					$nextpos = $physpos + $msminbases;
					
				}
			}
		}
	}
	else { @markerlist = @maptmp;}
	
	my $var = $#markerlist +1;	
	ShowOutput( "\t$var markers selected\nDone\n");
	$status_markerlist = 1;
}


##############################  P R I N T   G R R F I L E   ###########################
sub PrintGRRFile {
	
   if ($statusdata == 0) {
    	Errormsg("No data loaded!\nPlease enter genotypefile and read files!\n");
		return;
	}
	if ($statusped == 0){&ReadPedfilePro;}
	if ($statusmap == 0){&ReadGenMap;}

	my @grrlist=();
	my $lastchrom="XXX";
	my $nextpos= 0.;
	my $maxfreq=1-$minfreq;
	my @simdata=();

	ShowOutput( "\nSelect markers for Graphical Relationship Representation\n");
	ShowOutput( "\tminimal distance between markers : $minbases\n");
	ShowOutput( "\tminimal minor allele frequency   : $minfreq\n");
	
	foreach (@koord) {	# select SNPs from genetic map with high minor allele frequency

		my ($chrom,$marker,$genpos,$physpos,@rest)=split('\t',$_);
		next if $chrom eq /'NA'|''/;
		next if $chrom =~ /---/;
		if ($chrom == 23) {last;}
		if ($chrom ne $lastchrom) {
			$lastchrom = $chrom;
			$nextpos = 0.;
		}
		if (($physpos >= $nextpos) && (exists ($freqA{$marker}))) {
			if  ($freqA{$marker} > $minfreq and $freqA{$marker} < $maxfreq) {
				push (@grrlist,$marker);
				if ($simgrr ==1) {
					push (@simdata,"$marker\t$chrom\t$genpos\t$freqA{$marker}\t$freqB{$marker}");
				}
				$nextpos += $minbases;
			}
		}
	}
	my $var = $#grrlist +1;	
	ShowOutput( "\t$var autosomal markers selected\n");

	open (fhout,"> $grrfile") || die "could not open GRR file $grrfile :$!\n";

	for (my $i=1;$i<=$count;$i++) {	# for each Individuum in Pedfile.pro
		my $c=0;
		print fhout "$pedcheck[$i] ";
		foreach my $marker (@grrlist) {		# fr jeden SNP in der Liste

			if (! $gtype{$ind[$i]}{$marker}) { # No Hash if not genotyped
				print fhout " 0/0";
			}
			else {	# if genotyped then recode the Hash value and print
				if 	  (($gtype{$ind[$i]}{$marker} eq "AA")||($gtype{$ind[$i]}{$marker} eq "A"))  {print fhout " 1/1";}
				elsif (($gtype{$ind[$i]}{$marker} eq "BB")|| ($gtype{$ind[$i]}{$marker} eq "B"))  {print fhout " 2/2";}
				elsif ($gtype{$ind[$i]}{$marker} eq "AB") {print fhout " 1/2";}
				elsif (($gtype{$ind[$i]}{$marker} eq "NC")||($gtype{$ind[$i]}{$marker} eq "NoCall")) {print fhout " 0/0";}
				else {print fhout " X/X";}
			}
			$c++;
		}
#		print "$pedcheck[$i]\t\tgenotypes: $c\n";
		print fhout "\n";
	}
	close (fhout);
	
	ShowOutput( "GRR file saved in $grrfile\n");
	print "GRR file saved in $grrfile\nDone \n";

	if ($simgrr ==1) {
		my $simdatout="merlin.dat";
		my $simmapout="merlin.map";
		my $simfreqout="merlin.freq";
		open (DATOUT,"> $simdatout") || die "could not open dat file $simdatout :$!\n";
		open (MAPOUT,"> $simmapout") || die "could not open map file $simmapout :$!\n";
		open (FREQOUT,"> $simfreqout") || die "could not open freq file $simfreqout :$!\n";
		foreach (@simdata) {
			my @z=split('\t',$_);
			print DATOUT "M  $z[0]\n";
			print MAPOUT "$z[1]  $z[0]  $z[2]\n";
			print FREQOUT "M  $z[0]\nF $z[3] $z[4]\n";
		}
		print  DATOUT "E  END-OF-DATA\n";
		close (DATOUT);
		close (MAPOUT);
		close (FREQOUT);
	}
}


##############   P R I N T   M E R L I N   S I M U L A T I O N   ###############
sub PrintSimuFiles {
	my $z=0;
	my $c=0;
	my %genotyp=();
	if ($statusped == 0){&ReadPedfilePro;}
	if ($statusmap == 0){&ReadGenMap;}
	if ($del_errors == 1) {&DelErrors;}
	if ($del_unlikely == 1) {&DelUnlikely;}

	&InitializeSkiplist;

	if ($merlin_all_trait eq "withTrait") { $targetdir="merlin_all";}
	else {$targetdir="merlin_all_no_trait"; }
	
	if (! -d $targetdir) { mkdir ($targetdir,0777); ShowOutput("Create directory $targetdir\n");}
	else {Errormsg("Directory $targetdir exists. Please rename or delete it.\n");return;}
	
##	
	print "Create Merlin Files\n";
	my $var=$#autolist+1;
	print "Autosomal list has $var entries\n";

	open (fhout,"> $targetdir/merlin.ped") || die "could not open merlin.ped :$!\n";
	open (fhmap,"> $targetdir/merlin.map") || die "could not open merlin.map :$!\n";
	open (fhdat,"> $targetdir/merlin.dat") || die "could not open merlin.dat :$!\n";
	open (fhfrq,"> $targetdir/merlin.freq") || die "could not open merlin.freq :$!\n";

	if ($merlin_all_trait eq "withTrait") { print fhdat "A  Trait\n"; }

	foreach (@autoarray) {			# for each autosomal SNP in map
		my ($chrom,$marker,$genpos,$phypos,@rest)=split('\t',$_);

		$z++;
		### Skip SNPs in skiplist
		if (exists $skiplist{$marker}) {next;}
		
		if (! $gnames{$marker}){next;}	# Skip if marker not in GDAS genotype file
		$genotyp{dummy}.=" 0 0";
		while (my ($key,$value)= each (%sample)) {
			if (! $gtype{$value}{$marker}) { # No Hash if not genotyped
				$genotyp{$value}.=" x/x";	# then genotype is zero
			}
			else {	# if genotyped then recode the Hash value and print
				if	  (($gtype{$value}{$marker} eq "AA")||($gtype{$value}{$marker} eq "A"))  {$genotyp{$value}.=" 1/1";}
				elsif (($gtype{$value}{$marker} eq "BB")||($gtype{$value}{$marker} eq "B"))  {$genotyp{$value}.=" 2/2";}
				elsif ($gtype{$value}{$marker} eq "AB") {$genotyp{$value}.=" 1/2";}
				elsif ($gtype{$value}{$marker} eq "NC") {$genotyp{$value}.=" x/x";}
				else {$genotyp{$value}.=" X/X";}
			}
		}
		printf fhmap ("%3s %11s %12.8f\n",$chrom,$marker,$genpos);
		print fhdat "M  $marker\n";
		print fhfrq "M  $marker\n";
		if ($freqA{$marker}) {print fhfrq "F $freqA{$marker} $freqB{$marker}\n";}
		else {print fhfrq "F 0.500 0.500\n";}	# allele frequencies
		$c++;
	}
	print fhdat "E  END-OF-DATA\n";
	for (my $i=1;$i<=$count;$i++) {
		if ($merlin_all_trait eq "noTrait") { print fhout "$pedcheck[$i] "; }
		else { print fhout "$pedfile[$i] ";}
		if (! $genotyp{$ind[$i]}) {print fhout "$genotyp{dummy}\n";}
		else { print fhout "$genotyp{$ind[$i]}\n";}
	}
	close (fhout);
	close (fhmap);
	close (fhdat);
	close (fhfrq);
	print "From $z markers in map $c are used\nDone\n\n";
	ShowOutput( "Create Files done\n");
	
}

############################  C H E C K   G E N D E R   #########################

sub CheckGender {
    if ($statusdata == 0) {
    	Errormsg("No data loaded!\nPlease enter genotypefile and read files!\n");
		return;
	}
	print "Check gender";
	ShowOutput("\nCheck gender of individuals\n");
	
	my $var=0;
	my $sex="";
	my $del=0;
	my %het_male=();
	my %het_snp=();
	my %hetero=();		# counter heterozygote genotypes for each sample
	my %allgtps=();		# counter all genotypes of a sample (key)
	if ($statusmap==0) {&ReadGenMap;}
	foreach $marker (@xlist) {			# fr jeden SNP in der Markerkarte
		foreach $var (values %sample) {
			if (exists ($gtype{$var}{$marker})) {
				if ($gtype{$var}{$marker} ne "NC")  {$allgtps{$var}++;}
				if ($gtype{$var}{$marker} eq "AB") {
					$hetero{$var}++;
					if ($gender{$var} ==1){
						$het_snp{$marker}++;
						$het_male{$var}++;
						delete ($gtype{$var}{$marker});
						$del++;
					}
				}
			}
		}
	}
	ShowOutput("\nCount heterozygote genotypes on X-chromosome\n\n");
	ShowOutput("Sample\t\tCounts\n");
	ShowOutput("pid ----- het ----- % - genotyped ---- sex ---------\n");
	foreach my $key (sort {$a<=>$b} keys %allgtps) {
		if (! $hetero{$key}) {$var=0.0}
		else {$var=$hetero{$key}/$allgtps{$key}*100;}
		$var=sprintf("%4.1f",$var);
		if ($var > 7) {$sex = "Female";} else {$sex="Male";}
		ShowOutput("$key:\t$hetero{$key}\t$var\t$allgtps{$key}\t$sex");
		if (($gender{$key} ==1) && ($sex eq "Female")) {ShowOutput("\t### Male in pedfile!!!\n");}
		elsif (($gender{$key} ==2) && ($sex eq "Male")) {ShowOutput("\t### Female in pedfile!!!\n");}
		else {ShowOutput("\n");}

	}

	ShowOutput("\nX-linked marker heterozygote in male:\n");
	foreach my $marker (keys %het_snp){
		ShowOutput("\t$marker\t$het_snp{$marker}\n");
	}
	ShowOutput("\nmale individuals with heterozygote X-linked genotypes:\n");
	foreach my $key (keys %het_male){
		ShowOutput("$key\t$het_male{$key}\n");
	}
	print " done\n\n";
	if ($del == 1) {ShowOutput("\n$del genotype deleted\n");}
	elsif ($del > 1) {ShowOutput("\n$del genotypes deleted\n");}
	else {;}
	ShowOutput("\nCheck gender done\n");	
}

########################  M A K E  G R A F I C S  A L L  #######################
sub MakeGraficsAll {
	my $lastchrom="00";
	my $lastpos=0.;		# on current chromosome
	my $lastline="XXXX"; 
	my $lastxsum=0.;
	my $xmin = 0;
	my $xsum=.0;
	my $xmax=.0;
	my $ymin=0;
	my $ymax=1;
	my $chrlength=0;
	my $titel="";
	my $postfile="";
	$c_snperr=0;
	my @xsums=();
	%hashpos=();
	%hashchr=();
	my %chrlabel=();
	print "Sub MakeGraficsAll\n";

	open (OUT1, "> $valuesfile") || print "could not open valuefile $valuesfile :$!\n";

	foreach (@koord) {
		my @v = split('\t',$_);
		if (($v[0] =~ /---/) || ($v[0] eq "") || ($v[0] eq "NA")) {next;}

		if (($v[2] <= $lastpos) && ($v[0] eq $lastchrom)) {
			$posi= sprintf("%-8.5f",$lastpos+0.00002);
		}
		else { $posi= sprintf("%-8.5f",$v[2]);
		}
		$lastpos=$posi;	#
		$lastline=$_;

		if ($v[0] ne $lastchrom) {
			$xsum += $xmax;
			####---- print label ---###
			if ($lastchrom ne "00"){
				print "$lastchrom\t$xsum\n";
				my $xpos=(($lastxsum + $xsum)/2);
				my $var=$lastchrom; $var =~ s/^0//;
				if ($var eq "23"){$var = "X";}
				if ($var eq "24"){$var = "XY";}
				if ($var > 9){ $xpos -=30;}
				else { $xpos -=5;}
				$chrlabel{$var}=$xpos;	  
				$lastxsum=$xsum;
				push (@xsums,$xsum);###

			}

			$lastchrom=$v[0];
		}
		$xmax=$posi;
		if (exists $c_snp{$v[1]}) {
			$hashpos{$v[1]}=$posi;	# value - coord, key - SNP
			$hashchr{$v[1]}=$v[0];	# value - chrom, key - SNP
			printf OUT1 ("%8.5f %s\n", ($xsum + $posi),'0');
			printf OUT1 ("%8.5f %s \n\n", ($xsum + $posi),$c_snp{$v[1]});
			if ($c_snp{$v[1]} > $ymax) {$ymax = $c_snp{$v[1]};}
			$c_snperr++;
		}
	}
	$xsum += $xmax;
	print "$lastchrom\t$xsum\n";
	my $xpos=(($lastxsum + $xsum)/2);
	my $var=$lastchrom; $var =~ s/^0//;
	if ($var eq "23"){$var = "X";}
	if ($var eq "24"){$var = "XY";}
	if ($var > 9){ $xpos -=30;}
	else { $xpos -=5;}
	$chrlabel{$var}=$xpos;	  
	push (@xsums,$xsum);
	
	close (OUT1);

###-----------------------   m y p l o t . g p  --------------------###
	my $fams="";
	my $fc=0;
	foreach my $key (sort keys %famlist) {
		$fams .= "_$key";
		print "Familie: $key\n";
		$fc++;
	}
	if ($fc < 6) {
		$titel ="${basename}  $c_snperr SNPs have mendelian errors in Fam:${fams} ";
		$snperrfile="${base_no_ext}_Fam${fams}\.out";
		$postfile="${base_no_ext}_Fam${fams}\.ps";
	}
	else {
		$titel ="${basename}  $c_snperr SNPs have mendelian errors in ${fc} families ";
		$snperrfile="${base_no_ext}_${fc}_fams\.out";
		$postfile="${base_no_ext}_${fc}_fams\.ps";		
	}
#	$xsum=($xsum + $xmax);
	$ymax++;		# y-achse um 1 erhoehen bringen

###-----------------   P R I N T  C H R _ L I N E S   --------------------###
	open (OUT3,"> $chrfile") || die "could not open chr_line $chrfile :$!\n";

#	for (my $i=1; $i<$ymax;$i++) {	# Linien bei LODs = 1,2,3,4,..
#		print OUT3 "0 $i\n$xsum $i\n\n";
#	}
	pop (@xsums);
	foreach (@xsums){	# Linien Chromosomenende 1,2,3,4,...22,x,xy
		print OUT3 "$_ $ymin \n$_ $ymax \n\n";         
	}
	close (OUT3);

###----------------  P R I N T   G N U P L O T  B A T C H  --------------###

	open (OUT, "> $plotfile") || print "could not open $plotfile :$!\n";

	print OUT "set autoscale\n";
	print OUT "set title \"$titel\\n\"\n" ;
	print OUT "set xlabel \"cM\"\n";
	print OUT "set ylabel \"Counts\"\n";
	my $ypos = $ymax + (($ymax-$ymin)/20);
	foreach (keys %chrlabel) {print OUT "set label \"$_\" at $chrlabel{$_}\,$ypos\n";}
	print OUT "set size 1,0.8\n";
	print OUT "set terminal postscript color solid 11\n";
	print OUT "set output \"$postfile\n";
	print OUT "plot \[$xmin\:$xsum\] \[$ymin\:$ymax\]  \'$chrfile\' notitle with lines lt 0, \'$valuesfile\' title 'counts' with lines lt 1\n";
	if ( $command_line == 0) {
		print OUT "set terminal $terminal\n";
		print OUT "replot\n";
		print OUT "pause -1 \"Hit return to continue\"\n\n";
	}
	close (OUT);
}

########################  M A K E  G R A F I C S  O N E  #######################
sub MakeGraficsOne {
	my $lastpos=-0.5;
	my $xmin = 0;
	my $xmax=.0;
	my $ymin=-0.5;
	my $ymax=1;
	%hashpos=();
	%hashchr=();
	print "Sub MakeGrafics\n";

	open (OUT1, "> $valuesfile") || print "could not open valuefile $valuesfile :$!\n";
#	open (OUT2, "> $snpaffhet") || print "could not open  snpaffhet $snpaffhet :$!\n";
	foreach (@koord) {
		next if (substr($_,0,2) ne $pchrom);
		my @v = split('\t',$_);
		if ($v[2] <= $lastpos) {
			$posi= sprintf("%-8.5f",$lastpos+0.00002);
		}
		else {	$posi= sprintf("%-8.5f",$v[2]);}
		$lastpos=$posi;	#

		$xmax=$posi;
		if (! $c_snp{$v[1]} ) {	# Print all markers in map without error
			printf OUT1 ("%8.5f %s\n",$posi,'0.');
			printf OUT1 ("%8.5f %s\n\n",$posi,'-0.2');
		}
		else {	# Mendelerrors
			$hashpos{$v[1]}=$posi;	# value - coord, key - SNP
			$hashchr{$v[1]}=$v[0];	# value - chrom, key - SNP
			printf OUT1 ("%8.5f %s\n",$posi,'0');
			printf OUT1 ("%8.5f %s \n\n",$posi,$c_snp{$v[1]});
			if ($c_snp{$v[1]} > $ymax) { $ymax = $c_snp{$v[1]};}
		}
#		if ($snphet{$v[1]}) {	# affected are heterozygote
#			printf OUT2 ("%8.5f %s\n",$posi,'0');
#			printf OUT2 ("%8.5f %s \n\n",$posi,$snphet{$v[1]});
#			if ($snphet{$v[1]} > $ymax) { $ymax = $snphet{$v[1]};}
#		}
	}

	close (OUT1);
#	close (OUT2);

###-----------------------   m y p l o t . g p  --------------------###
	my $fc=0;
	my ($titel,$postfile,$fams);
	
	foreach my $key (sort keys %famlist) {
		$fams .= "_$key";
		print "Familie: $key\n";
		$fc++;
	}
	if ($fc < 6) {
		$titel ="${basename}  mendelian errors in fam:${fams} chromosome $pchrom ";
		$snperrfile="${base_no_ext}_fam${fams}_chr$pchrom\.out";
		$postfile="${base_no_ext}_fam${fams}_chr$pchrom\.ps";
	}
	else {
		$titel ="${basename}  mendelian errors in ${fc} families chrom $pchrom  ";
		$snperrfile="${base_no_ext}_fams_${fc}_chr$pchrom\.out";
		$postfile="${base_no_ext}_fams_${fc}_chr$pchrom\.ps";		
	}

	$xmax=$posi;
	$ymax ++;
	open (OUT, "> $plotfile") || print "could not open $plotfile :$!\n";

	print OUT "set autoscale\n";
	print OUT "set title \"$titel\"\n" ;
	print OUT "set xlabel \"cM\"\n";
	print OUT "set ylabel \"Counts\"\n";
	print OUT "set size 1,0.6\n";
	print OUT "set terminal postscript colour solid\n";
	print OUT "set output \"$postfile\n";
	print OUT "plot \[$xmin\:$xmax\] \[$ymin\:$ymax\]  \'$valuesfile\' title 'counts' with lines\n";
	print OUT "set terminal $terminal\n";
	print OUT "replot\n";
	print OUT "pause -1 \"Hit return to continue\"\n\n";

	close (OUT);

}

#######################   P R I N T  E R R O R  L I S T    #####################
sub PrintErrList {
	my $c_nop=0;
	open (OUT, "> $snperrfile") || print "could not open $snperrfile :$!\n";
	foreach my $key (keys %c_snp) {
		if (! $hashpos{$key}) {
			printf ("%2s %9.5f\t%-13s %2s %s\n",'---','---',$key,$c_snp{$key});
			$c_nop++;
		}
		else {
			printf OUT ("%2s %9.5f\t%-13s %2s\n",$hashchr{$key},$hashpos{$key},$key,$c_snp{$key});
		}
	}
	close (OUT);

	print "Print errfile: $snperrfile\n";
	system "sort $snperrfile > errors.srt";	# Sort SNP errors by "Chrom, Position"

	open (OUT, "> $snperrfile") || print "could not open $snperrfile :$!\n";
	print OUT "# SNPs with Mendelian errors identified by PedCheck\t\t$datum\n\n";
	print OUT "# Infile:\t$infile\n\n";
	print OUT "chr  pos\tSNP_ID\tcounts\n";

	open (IN, "errors.srt") || print "could not open errors.srt :$!\n";
	my $last="XX";
	while (<IN>){
		next if /^$/;		# skip blank line
		if (substr($_,0,2) ne $last) {
			print OUT "\n";
			$last = substr($_,0,2);
		}
		print OUT "$_";
	}
	print OUT "\n$c_snp_err SNPs have $c_err errors";
	if ($c_nop > 0) { print OUT " \($c_nop SNPs w/o position\)\n";}
	else {print OUT "\n";}
	close (IN);
	close (OUT);
}


##########################  Print SNP groups with small distances ###########
sub PrintHapBlocks {
	my $lastchrom="XYZ";
	my $lastpos;
	my $var="";
	my $diff=0;
	my ($chrom,$marker,$genpos,$phypos,@rest);

	ShowOutput("\nPrint HapBlocks file\n");

	open (OUT, "> HapBlockFile.txt") || print "could not open HapBlockFile.txt :$!\n";
	print OUT "CHR\tMarker\tGenPos\tPhysPos\tFreqA\tFreqB\tDiff\n";

	foreach (@koord) {			# fr jeden SNP in der Markerkarte
		($chrom,$marker,$genpos,$phypos,@rest) = split('\t',$_);
		if (($chrom eq "") || ($chrom eq "NA")) {next;}
		$var="$chrom\t$marker\t$genpos\t$phypos\t$freqA{$marker}\t$freqB{$marker}";	###
		print OUT "$var";
		if ($chrom eq $lastchrom){
			$diff= $phypos-$lastpos ;
			if ($diff < 40000){
				print OUT "\t$diff\t\#\#\#\n";
			}
			else {print OUT "\n";}
		}
		$lastchrom=$chrom;
		$lastpos=$phypos;
	}

	close (OUT);	
	print "\nPrint HapBlock File done\n\n";
	ShowOutput("\nPrint HapBlock File done\n\n");

}


#######################  C O M P A R E  S A M P L E IDs  ######################
##################### in pedfile.pro with GDAS genotype file  #################
sub CompareSampleIDs {
    if ($statusdata == 0) {
    	Errormsg("No data loaded!\nPlease enter genotypefile and read files!\n");
		return;
	}
	my @v=();	# sampleIDs in pedfile.pro but not in genotype file
	foreach (sort keys %indiv){if (! $samples{$_}) {push(@v,$_);}}
	ShowOutput("\nSamples in pedfile.pro, but not in genotype file:");
	if ($#v < 0) {ShowOutput(" none\n");}
	else {ShowOutput("\n@v\n");}

	@v=();		# sampleIDs in genotype file, but not in pedfile.pro
	ShowOutput("\nSamples in genotype file, but not in pedfile.pro:");
	foreach (sort keys %samples){if (! $indiv{$_}) {push(@v,$_);}}
	if ($#v < 0) {ShowOutput(" none\n");}
	else {ShowOutput("\n@v\n");}
	
	@v=();		# search for doubled sampleIDs in genotype file
	foreach (sort keys %samples){if ($samples{$_} > 1) {push(@v,$_);}}
	ShowOutput("\nDoubled sample IDs in genotype file:");
	if ($#v < 0) {ShowOutput(" none\n");}
	else {ShowOutput("\n@v\n");}

	@v=();		# search for doubled sampleIDs in pedfile.pro
	foreach (sort keys %indiv){ if ($indiv{$_} > 1) {push(@v,$_);}}
	ShowOutput("\nDoubled sample IDs in pedfile:");
	if ($#v < 0) {ShowOutput(" none\n");}
	else {ShowOutput("\n@v\n");}
}

######################  L I N K A G E  F O R M A T  F I L E S  #################
sub Allegro {
	$selection="allegro";
	if ($command_line == 0) { MW2LinkageFiles(); }
	else { &MakeLinkageFiles; }
}

sub Fbat {
	$selection="fbat";
	if ($command_line == 0) { MW2LinkageFiles(); }
	else { &MakeLinkageFiles; }
}

sub Genehunter {
	$selection="gh";
	if ($command_line == 0) { MW2LinkageFiles(); }
	else { &MakeLinkageFiles; }
}

sub Haploview {
	$selection="haploview";
	if ($command_line == 0) { MW2LinkageFiles(); }
	else { &MakeLinkageFiles; }
}

sub Merlin {
	$selection="merlin";
	if ($command_line == 0) { MW2LinkageFiles(); }
	else { &MakeLinkageFiles; }
}

sub Mega2 {	
	if (@ind =~ /\-|\./) {
		print "Pedfile.pro: Non-numeric character in Person ID. Mendel-format requires integer ids.\n@ind\n";
		ShowOutput("\nPedfile.pro: Non-numeric character in Person ID. Mendel-format requires integer ids.\n");
		return;
	}
	$selection="mega2";
	if ($command_line == 0) { MW2LinkageFiles(); }
	else { &MakeLinkageFiles; }
}

sub Plink {
	$selection="plink";
	if ($command_line == 0) { MW2LinkageFiles(); }
	else { &MakeLinkageFiles; }
}




####################  M A K E   L I N K A G E   F I L E S     ##################
sub MakeNoLimitFiles {
	$all_markers=0;
	my $aref;
	print "Sub MakeNoLimitFiles\n";
	my $lastgenpos="0";
	$lastchrom="00";
	if ($status_markerlist == 1) { $aref = \@markerlist ;}
	else { 
		&InitializeSkiplist;	
		$aref = \@koord;
	}


LINE4: foreach (@$aref) {			# for each SNP in genetic map
		my ($chrom,$marker,$genpos,$phypos,@rest) =split('\t',$_);

		if (exists $skiplist{$marker}) {next LINE4;}

		if ($chrom eq "") {next LINE4;}
		if ( uc($chrom) eq "NA") {next LINE4;}
		if ($chrom =~ /---/) {next LINE4;}
		if ($chrom ne $lastchrom) {
			if ($lastchrom ne '00') {
				&PrintNoLimitFiles;
			}
			$chr_dir="c$chrom";

			if (! -d "$targetdir/$chr_dir" ) {mkdir ("$targetdir/$chr_dir",0777);}
			$lastchrom=$chrom;
			$lastgenpos=-0.1;
			$nr=0;
			@mapout=();
			%genotyp=();
		}

		if ($gnames{$marker}){	# Is this marker in genotypefile list?
			$nr++;
			if (($genpos <= $lastgenpos) && ($chrom eq $lastchrom)) {
				$genpos=$lastgenpos+0.0001;
			}
			$lastgenpos=$genpos;	#
			if (($aliasname eq "rs-number") && (exists $alias{$marker})) { 			
				push (@mapout,"$chrom\t$genpos\t$alias{$marker}\t$phypos\t$nr");
				$freqA{$alias{$marker}}=$freqA{$marker};
				$freqB{$alias{$marker}}=$freqB{$marker};
			}
			else { 
				push (@mapout,"$chrom\t$genpos\t$marker\t$phypos\t$nr");
			}

			$genotyp{dummy}.=" 0 0";
			while (my ($key,$value)= each (%sample)) {

				if (! $gtype{$value}{$marker}) { # Not in Hash if not genotyped
					$genotyp{$value}.=" 0 0";
				}
				else {	# if genotyped then recode the Hash value and print
					if	  (($gtype{$value}{$marker} eq "AA")||($gtype{$value}{$marker} eq "A"))  {$genotyp{$value}.=" 1 1";}
					elsif (($gtype{$value}{$marker} eq "BB")||($gtype{$value}{$marker} eq "B"))  {$genotyp{$value}.=" 2 2";}
					elsif ($gtype{$value}{$marker} eq "AB") {$genotyp{$value}.=" 1 2";}
					elsif ($gtype{$value}{$marker} eq "NC") {$genotyp{$value}.=" 0 0";}
					else {$genotyp{$value}.=" 0 0";
						print "unknown genotype: $gtype{$value}{$marker} : $value : $marker\n";
					}
				}
			}
		}
	}
	&PrintNoLimitFiles;
	ShowOutput("$all_markers SNPs are used on all chromosomes\n");
	ShowOutput("Linkage files created\n\n");
	print "Linkage files created\n\n";
	&WriteLog;
}

####################  P R I N T   G E N E H U N T E R   F I L E S     #################
####################         and       M E G A 2        F I L E S     #################

sub PrintNoLimitFiles {
	my @recomb_list=();		# datain: marker distance in recombination fraction
	my @ghuse=();			# genehunter setup markerlist
	my @mendel_map=();		# mendel4.1 markermap
	my $pedfile="$targetdir/$chr_dir/pedin\.$lastchrom";
	my $mapfile="$targetdir/$chr_dir/map\.$lastchrom";
	my $merl_mapfile="$targetdir/$chr_dir/merlin_map\.$lastchrom";
	my $hapview_mapfile="$targetdir/$chr_dir/haploview_map\.$lastchrom";
	my $mend_mapfile="$targetdir/$chr_dir/mendel_map\.$lastchrom";
	my $plink_mapfile="$targetdir/$chr_dir/plink_map\.$lastchrom";
	my $datfile="$targetdir/$chr_dir/datain\.$lastchrom";
	my $setupfile="$targetdir/$chr_dir/setup\.$lastchrom";
	my $mendel4controlfile="$targetdir/$chr_dir/control\.$lastchrom";
	my ($diff, $theta, @v, @z);
	$all_markers += $nr;# Sum of all markers on all chromosomes used for analysis

	print "Mapfile: $mapfile\n";
	ShowOutput("create: $mapfile\n");

#-------------------------------pedfile-----------------------------###
	open (OUT,"> $pedfile") || die "could not open $pedfile :$!\n";
	if ($qtl_select == 1){
		for (my $i=1;$i<=$count;$i++) {
			print OUT "$pedfile[$i] ";		# including affection status

			if (! $genotyp{$ind[$i]}) {print OUT "$genotyp{dummy}";}
			else { print OUT "$genotyp{$ind[$i]}";}

			###### QTL traits ######
			if (! $qtltraits{$ind[$i]}) {
				for (my $j=1;$j<=$c_traits;$j++){
					if ($selection eq "merlin") { print OUT " x";}
					else { print OUT " -";}	# what is unknown phenotype in linkage format?
				}				
			}
			else {
				my @v=split(' ',$qtltraits{$ind[$i]});
				for (my $j=1;$j<=$c_traits;$j++){
					print OUT " $v[$j]";
				}
			}
			###### end QTL traits ######
			print OUT "\n";
		}		
	}
	else {		# qualitative trait #

		if ($targetdir eq "fbat") {	# only for FBAT
			foreach (@mapout) {
				my @z=split('\t',$_);
				print OUT " $z[2]";
			}
			print OUT "\n";
		}
		
		for (my $i=1;$i<=$count;$i++) {
			print OUT "$pedfile[$i] ";
			if (! $genotyp{$ind[$i]}) {print OUT "$genotyp{dummy}\n";}
			else { print OUT "$genotyp{$ind[$i]}\n";}
		}
	}
	close (OUT);

#-------------------------------mapfile------------------------------###
	open (OUT,"> $mapfile") || die "could not open $mapfile :$!\n";
	print OUT "#Chr     Genpos       Marker     Physpos    Nr\n";
	foreach (@mapout) {
		my @z=split('\t',$_);
		printf OUT ("%3s  %12.8f %11s %10s %5s\n",$z[0],$z[1],$z[2],$z[3],$z[4]);
	}
	close (OUT);

#---------------------------  mapfile Haploview  ----------------------------###
	if ($targetdir =~ /haploview/) {
		open (OUT,"> $hapview_mapfile") || die "could not open $hapview_mapfile :$!\n";
		foreach (@mapout) {
			my @z=split('\t',$_);
			printf OUT ("%s\t%s\n",$z[2],$z[3]);
		}
		close (OUT);
	}

#-------------------------------mapfile merlin------------------------------###
	if ($targetdir eq "merlin") {
		open (OUT,"> $merl_mapfile") || die "could not open $merl_mapfile :$!\n";
		print OUT "#Chr    Marker    Position\n";
		foreach (@mapout) {
			my @z=split('\t',$_);
			printf OUT ("%3s %11s %12.8f\n",$z[0],$z[2],$z[1]);
		}
		close (OUT);
	}

#------------------------------- mapfile plink ------------------------------###
	if ($targetdir eq "plink") {
		open (OUT,"> $plink_mapfile") || die "could not open $plink_mapfile :$!\n";
#		print OUT "#Chr    Marker   Genetic_pos Phys_pos\n";
		foreach (@mapout) {
			my @z=split('\t',$_);
			printf OUT ("%3s %13s %12.8f %10d\n",$z[0],$z[2],$z[1],$z[3]);
		}
		close (OUT);
	}
#-------------------------------datafile------------------------------###
	my $no_loci=$nr+1; 	# markers + trait	
	if ($qtl_select == 1) { $no_loci=$nr+1 + $c_traits; }
	my $lastpos=-1;		# first interval for recombination rate

	open (OUT,"> $datfile") || die "could not open $datfile :$!\n";
	if ($lastchrom == 23) { print OUT "$no_loci 0 1 5\n";}
	else {print OUT "$no_loci 0 0 5\n";}
	print OUT " 0 0.0 0.0 0 \n";
	for (my $i=1;$i<=$no_loci;$i++){
		print OUT " $i";
	}

	print OUT "\n1  2 \t# TRAIT\n";	# default genetic model
	print OUT " $fp $fq\n";
	print OUT " 1\n";

	if ($gh_imp == 0) {
		print OUT " $pvf1 $pvf2 $pvf3\n";
		if ($lastchrom == 23) { print OUT " 0.001 0.990\n";}
	}
	else {
		print OUT " $pvf1 $pvf2 $pvf3 $pvf4\n";
		if ($lastchrom == 23) { print OUT " 0.001 0.990\n";}
	}

	foreach (@mapout) {
		my @z=split('\t',$_);
		my $theta=0;
		print OUT "3  2 \t# $z[2]\n";
		if ($freqA{$z[2]}) {print OUT " $freqA{$z[2]} $freqB{$z[2]}\n";}
		else {print OUT " 0.500 0.500\n";}	# allele frequencies
		if ($lastpos == -1) { 	# first interval
			push (@recomb_list," 0.1");
			push (@ghuse,"use $z[2]");
			push (@mendel_map,"$z[2]");

		}
		else {
			my $diff =sprintf("%10.6f",($z[1] - $lastpos));
			if ($diff < 0) { $diff=0.0001; print "$z[2] distance to last marker is negative\n";} # for some programs
			if ($diff == 0) { $diff=0.0001;} # for some programs
			if ($mapfunc eq "Kosambi") {	## Kosambi function	
				$theta=sprintf("%8.6f",(((exp(0.04*$diff))-1)/((exp(0.04*$diff))+1)/2) ); 	
			}
			else {						## Haldane Funktion
				$theta=sprintf("%8.6f",((1-exp(-(2 * $diff/100))) / 2)); 
			}
			if ($theta == 0) {$theta= 0.000001;} # print "$z[2] distance: $diff  theta eq $theta, inserted 0.000001\n";}
			push (@recomb_list," $theta");
			push (@ghuse,"$diff $z[2]");
			push (@mendel_map,"        $theta");
			push (@mendel_map,"$z[2]");
		}
		$lastpos=$z[1];
	}
	#### QTL begin ####
	if ($qtl_select == 1) {
		for (my $j=1;$j<=$c_traits;$j++) {
			print OUT "0  2   \<\< QUANTITATIVE $qtlname{$j}, NO. OF ALLELES\n";	# default genetic model
			print OUT " $fp $fq  \<\< GENE FREQUENCIES\n";
			print OUT " 1 << NO. OF TRAITS\n";			
			print OUT "     0.000     0.000     0.000 << GENOTYPE MEANS\n";			
			print OUT "     1.000  << VARIANCE - COVARIANCE MATRIX\n";			
			print OUT "     1.000  << MULTIPLIER FOR VARIANCE IN HETEROZYGOTES\n";
			push (@recomb_list," 0.1");

		}		
	}
	print OUT " 0 0\n";
	print OUT "@recomb_list\n";
	print OUT " 1      2.0  1.0\n";
	close (OUT);

#-------------------------------mapfile mendel------------------------------###
  if ($targetdir eq "mendel") {
	open (OUT,"> $mend_mapfile") || die "could not open $mend_mapfile :$!\n";
	foreach (@mendel_map) {
	print OUT"$_\n";
	}
	close (OUT);

#--------------------------  mendel4_control.in------------------------------###

	open (OUT,"> $mendel4controlfile") || die "could not open $mendel4controlfile :$!\n";
	print OUT "OUTPUT_FILE=mendel.out\n";
	print OUT "LOCUS_FILE=locus\.$lastchrom\n";
	print OUT "MAP_FILE=mendel_map\.$lastchrom\n";
	print OUT "PEDIGREE_FILE=pedm\.$lastchrom\n";
	print OUT "SUMMARY_FILE=summary.out\n";
	print OUT "ANALYSIS_OPTION=Location_scores\n";
	print OUT "NUMBER_OF_MARKERS_INCLUDED=$#mapout\n";
	close (OUT);
  }
	
#-------------------------------gh_setup.in------------------------------###
  if ($targetdir eq "gh") {

	open (OUT,"> $setupfile") || die "could not open $setupfile :$!\n";
	print OUT "photo gh.out\n";
	print OUT "load markers $datfile\n";
	print OUT "use\n";
	print OUT "ps off\n";
	print OUT "score\n";
	print OUT "haplo on\n";
	print OUT "discard off\n";
	print OUT "scan $pedfile\n";
	print OUT "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n";
	print OUT "ps on\n";
	print OUT "total stat het\n";
	print OUT "\n\n\n\n\n\n\nq\n";
	close (OUT);
  }
}
  
############   M A K E   L I N K A G E   S U B S E T   F I L E S   #############
sub MakeSubsetFiles {
	print "\nMake Subset Files\n";
	ShowOutput("\nMake Subset Files\n");

	my $w=0;
	my $cw=0;		# counts repeated markers in next set
	my $addd=0;		# last markerposition was increased ($addd=1)
	$all_markers=0;
	my $aref="";	# array reference on markermap
	@ghunix=();			# gh_start_sh unix
	@swunix=();			# sw_lod_start_sh unix
	@ghdos=();			# gh_start_bat DOS
	my $lastgenpos="0";
	$lastchrom="00";

	if ($status_markerlist == 1) { $aref=\@markerlist;}
	else {
		&InitializeSkiplist;
		$aref=\@koord;
	}


LINE3: for ($w=0;$w<=$#$aref;$w++) {			# fr jeden SNP in der Markerauswahl
		my ($chrom,$marker,$genpos,$phypos,@rest) =split('\t',$aref->[$w]);

		if (($chrom eq "")||($chrom eq "NA")||($chrom =~ "---")) {next LINE3;}

		# Skip not informative SNPs
		if ($skiplist{$marker}) {next LINE3;}

		if (($genpos < $lastgenpos)&& ($chrom eq $lastchrom) && ($nr > 0)) {
			if ($addd==0) {
				print "Position of marker $marker is smaller than last position. Alohomora inserts a small distance of 0.0001 cM!\n";
				ShowOutput("Position of marker $marker is smaller than last position. Alohomora inserts a small distance of 0.0001 cM!\n");
			}
			$genpos=$lastgenpos+0.0001;
	 		$addd=1;		
		}

		elsif (($genpos == $lastgenpos)&& ($chrom eq $lastchrom) && ($nr > 0)) {
			$genpos=$lastgenpos+0.0001; $addd=1;
			print "\tPosition of marker $marker is equal last position.\n\tAlohomora inserts a small distance of 0.0001 cM!\n";
			ShowOutput("\tPosition of marker $marker is equal last position.\n\tAlohomora inserts a small distance of 0.0001 cM!\n");
		}
		else {$addd=0;}


		$lastgenpos=$genpos;	#

		if ($chrom ne $lastchrom) {		# next chromosome
			if ($lastchrom ne '00') {
				&PrintSubsetFiles;
				push (@ghunix," cd ..\nfi\n\n");
				push (@ghdos,"\tcd ..\n\) else echo no chromosome $lastchrom\n\n");
				push (@swunix,"  cd ..\nfi\n\n");
			}
			$chr_dir="c$chrom";
			if (! -d "$targetdir/$chr_dir") {mkdir "$targetdir/$chr_dir",0777;}
			push (@ghunix,"if \[ -d $chr_dir \]\n then\n cd $chr_dir\n");
			push (@ghunix,"  rm *.ps *.out *.dump\n");
			push (@ghunix,"  d2uall\.sh\n");
			push (@swunix,"if \[ -d $chr_dir \]\n then\n  cd $chr_dir\n");
			push (@swunix,"  rm *VIDEO* *.out MEGA*\n");
			push (@swunix,"  d2uall\.sh\n");
			push (@swunix,"  echo \"1\" \> mega2_in.tmp\n");
			push (@swunix,"  echo \"$chrom\" >> mega2_in.tmp\n");
			push (@swunix,"  echo \"0\" >> mega2_in.tmp\n");
			push (@swunix,"  echo \"1\" >> mega2_in.tmp\n");	# Simwalk
			push (@swunix,"  echo \"2\" >> mega2_in.tmp\n");	# LODscore analysis
			push (@swunix,"  echo \"1\" >> mega2_in.tmp\n");
			push (@swunix,"  echo \"0\" >> mega2_in.tmp\n");
			push (@swunix,"  echo \"0\" >> mega2_in.tmp\n");
			push (@ghdos,"if exist $chr_dir \(\n\tcd $chr_dir\n");
			push (@ghdos,"\tdel *.ps *.out *.dump\n");
			$lastchrom=$chrom;
			$nr=0;
			@mapout=();
			%genotyp=();
			$vnr=0;
		}

		if ($gnames{$marker}) {
			$nr++;

### use alias marker names ###			
			if (($aliasname eq "rs-number") && (exists $alias{$marker})) { 
				push (@mapout,"$chrom\t$genpos\t$alias{$marker}\t$phypos\t$nr");
				$freqA{$alias{$marker}}=$freqA{$marker};
				$freqB{$alias{$marker}}=$freqB{$marker};
			}
			else { 
				push (@mapout,"$chrom\t$genpos\t$marker\t$phypos\t$nr");
			}
###			
		
#			push (@mapout,"$chrom\t$genpos\t$marker\t$phypos\t$nr");
			$genotyp{dummy}.=" 0 0";
			while ( my ($key,$value)= each (%sample)) {

				if (! $gtype{$value}{$marker}) { # Not in Hash if not genotyped,
					$genotyp{$value}.=" 0 0";	# then genotype is zero
				}
				else {	# if genotyped then recode the Hash value and print
					if	  (($gtype{$value}{$marker} eq "AA")||($gtype{$value}{$marker} eq "A"))  {$genotyp{$value}.=" 1 1";}
					elsif (($gtype{$value}{$marker} eq "BB")||($gtype{$value}{$marker} eq "B"))  {$genotyp{$value}.=" 2 2";}
					elsif ($gtype{$value}{$marker} eq "AB") {$genotyp{$value}.=" 1 2";}
					elsif ($gtype{$value}{$marker} eq "NC") {$genotyp{$value}.=" 0 0";}
					else {$genotyp{$value}.=" 0 0";
						print "unknown genotype: $gtype{$value}{$marker} : $value : $marker\n";
					}
				}
			}
		}
		if ($nr == $maxsnp) {
			&PrintSubsetFiles;
			$w--;
			$cw++;
			$nr=0;
			@mapout=();
			%genotyp=();
		}
	}
	if ($nr > 0) {
		&PrintSubsetFiles;
		push (@ghunix," cd ..\nfi\n\n");
		push (@ghdos,"\tcd ..\n\) else echo no chromosome $lastchrom\n\n");
		push (@swunix,"  cd ..\nfi\n\n");
	}

	if ($selection eq "gh"){
		my $batch="$targetdir/$gh_batch";
		open (OUT,"> $batch") || die "could not open gh_start_sh $batch :$!\n";
		foreach (@ghunix) {print OUT "$_";}
		close (OUT);
		$batch="$targetdir/$dos_batch";
		open (OUT,"> $batch") || die "could not open dos_start_sh $batch :$!\n";
		foreach (@ghdos) {print OUT "$_";}
		close (OUT);
	}

	if ($selection eq "mega2"){
		my $megabatch="$targetdir/$mega2swlod";
		open (OUT,"> $megabatch") || die "could not open mega2batch $megabatch :$!\n";
		foreach (@swunix) {print OUT "$_";}
		close (OUT);
	}
	print "\nMake Subset Files done\n\n";
	$all_markers -= $cw;
	ShowOutput("\nSNPs remain on all chromosomes: $all_markers\n");
	ShowOutput("\nMake Subset Files done\n\n");
	&WriteLog;
}


####################  P R I N T   S U B S E T   F I L E S     ##################

sub PrintSubsetFiles {
	$all_markers += $nr;
	$vnr++;
	my @recomb_list=();		# datain recombinationlist
	my @ghuse=();			# genehunter setup markerlist
	my $pedfile="pedin_$vnr.$lastchrom";
	my $mapfile="map_$vnr.$lastchrom";
	my $hapview_mapfile="haploview_map_$vnr.$lastchrom";
	my $plink_mapfile="plink_map_$vnr\.$lastchrom";
	my $datfile="datain_$vnr.$lastchrom";
	my $setupfile="setup_$vnr.$lastchrom";
	my $tdtfile="tdt_$vnr.$lastchrom";
	my $merl_mapfile="merlin_map_$vnr.$lastchrom";
	print "Mapfile: $mapfile\n";
	ShowOutput("  Mapfile: $mapfile\n");
	

#-------------------------------Genehunter BATCH------------------------###
  if ($selection eq "gh") {
	if ($lastchrom == 23) { push (@ghunix,"  xghi < $setupfile\n");push (@ghdos,"\txghi < $setupfile\n");}
	else {push (@ghunix,"  $gh_prog < $setupfile\n");push (@ghdos,"\t$gh_prog < $setupfile\n");}
	push (@ghunix,"  mv haplo.dump haplo_$vnr.dump\n");push (@ghdos,"\tmove haplo.dump haplo_$vnr.dump\n");
	if ($gh_tdt2 ==1) {push (@ghunix,"  mv ld.out ld_$vnr.out\n");push (@ghdos,"  move ld.out ld_$vnr.out\n");}
  }
#-----------------------------------MEGA2 BATCH-------------------------###
  if ($selection eq "mega2" ) {
	push (@swunix,"\n");
	push (@swunix,"  cp $pedfile pedin.$lastchrom\n");
	push (@swunix,"  cp $datfile datain.$lastchrom\n");
	push (@swunix,"  cp $mapfile map.$lastchrom\n");

	push (@swunix,"  mega2 < mega2_in.tmp\n");
	push (@swunix,"  if \[ -f loc.$lastchrom.sh \]\n");
	push (@swunix,"   then\n");
	push (@swunix,"    .\/loc.$lastchrom.sh\n");
	push (@swunix,"    mv SCORE-$lastchrom.ALL SCORE\-${lastchrom}_$vnr.ALL\n");
	push (@swunix,"  fi\n");
	push (@swunix,"  rm \*.out MEGA* \*.sh \n\n\n");
  }

#-------------------------------pedfile------------------------------###
	open (OUT,"> $targetdir/$chr_dir/$pedfile") || die "could not open $targetdir/$chr_dir/$pedfile :$!\n";

	if ($qtl_select == 1) {					
		for (my $i=1;$i<=$count;$i++) {
			print OUT "$pedfile[$i] ";		# including affection status

			if (! $genotyp{$ind[$i]}) {print OUT "$genotyp{dummy}";}
			else { print OUT "$genotyp{$ind[$i]}";}

			###### QTL traits ######
			if (! $qtltraits{$ind[$i]}) {
				for (my $j=1;$j<=$c_traits;$j++){
					if ($selection eq "merlin") { print OUT " x";}
					else { print OUT " -";}	# what is unknown phenotype in linkage format?
				}				
			}
			else {
				my @v=split(' ',$qtltraits{$ind[$i]});
				for (my $j=1;$j<=$c_traits;$j++){
					print OUT " $v[$j]";
				}
			}
			###### end QTL traits ######
			print OUT "\n";
		}		
	}
	else {		# qualitative trait

		if ($selection eq "fbat") {	# only for FBAT
			foreach (@mapout) {
				my @z=split('\t',$_);
				print OUT " $z[2]";
			}
			print OUT "\n";
		}

		for (my $i=1;$i<=$count;$i++) {
			print OUT "$pedfile[$i] ";
			if (! $genotyp{$ind[$i]}) {print OUT "$genotyp{dummy}\n";}
			else { print OUT "$genotyp{$ind[$i]}\n";}
		}
	}
	close (OUT);

#-------------------------------mapfile------------------------------###
	open (OUT,"> $targetdir/$chr_dir/$mapfile") || die "could not open $mapfile :$!\n";
	print OUT "#Chr    Genpos       Marker     Physpos    Nr\n";
	foreach (@mapout) {
		my @z=split('\t',$_);
		printf OUT ("%3s  %11.8f %11s %10s %4s\n",$z[0],$z[1],$z[2],$z[3],$z[4]);
	}
	close (OUT);

#-------------------------------mapfile merlin------------------------------###
	if ($selection eq "merlin") {
		open (OUT,"> $targetdir/$chr_dir/$merl_mapfile") || die "could not open $merl_mapfile :$!\n";
		print OUT "#Chr    Marker    Position\n";
		foreach (@mapout) {
			my @z=split('\t',$_);
			printf OUT ("%3s %11s %12.8f\n",$z[0],$z[2],$z[1]);
		}
		close (OUT);
	}

#------------------------------- mapfile plink ------------------------------###
	if ($selection eq "plink") {
		open (OUT,"> $targetdir/$chr_dir/$plink_mapfile") || die "could not open $plink_mapfile :$!\n";
		print OUT "#Chr    Marker    Genetic_pos  Phys_pos\n";
		foreach (@mapout) {
			my @z=split('\t',$_);
			printf OUT ("%3s %13s %12.8f %12d\n",$z[0],$z[2],$z[1],$z[3]);
		}
		close (OUT);
	}

#---------------------------  mapfile Haploview  ----------------------------###
	if ($selection eq "haploview") {
		open (OUT,"> $targetdir/$chr_dir/$hapview_mapfile") || die "could not open $hapview_mapfile :$!\n";
		foreach (@mapout) {
			my @z=split('\t',$_);
			printf OUT ("%s\t%s\n",$z[2],$z[3]);
		}
		close (OUT);
	}

#-------------------------------datafile------------------------------###
	my $no_loci=$nr+1;	# markers + trait
	if ($qtl_select == 1) { $no_loci=$nr+1 + $c_traits; }
	my $lastpos = -1;		# first interval for recombination rate

	open (OUT,"> $targetdir/$chr_dir/$datfile") || die "could not open $datfile :$!\n";
	if ($lastchrom == 23) { print OUT "$no_loci 0 1 5\n";}
	else {print OUT "$no_loci 0 0 5\n";}
	print OUT " 0 0.0 0.0 0 \n";
	for (my $i=1;$i<=$no_loci;$i++){
		print OUT " $i";
	}
	print OUT "\n1  2 \t# TRAIT\n";
	print OUT " $fp $fq\n";
	print OUT " 1\n";

	if ($gh_imp == 0) {
		print OUT " $pvf1 $pvf2 $pvf3\n";
		if ($lastchrom == 23) { print OUT " 0.001 0.990\n";}
	}
	else {
		print OUT " $pvf1 $pvf2 $pvf3 $pvf4\n";
		if ($lastchrom == 23) { print OUT " 0.001 0.990\n";}
	}

	foreach (@mapout) {
		my ($theta, $diff);
		my @z=split('\t',$_);
		print OUT "3  2 \t# $z[2]\n";
		if ($freqA{$z[2]}) {print OUT " $freqA{$z[2]} $freqB{$z[2]}\n";}
		else {print OUT " 0.500 0.500\n";}	# allele frequencies
		if ($lastpos == -1) { 	# first interval
			push (@recomb_list," 0.1");
			push (@ghuse,"use $z[2]");
		}
		else {
			$diff =sprintf("%9.6f",($z[1] - $lastpos));
			if ($diff == 0) { $diff=0.0001;} # for some programs
			if ($diff < 0) { $diff=0.0001; print "$z[2] distance to last marker is negative\n";} # for some programs
			if ($mapfunc eq "Kosambi") {	## Kosambi function	
				$theta=sprintf("%7.6f",(((exp(0.04*$diff))-1)/((exp(0.04*$diff))+1)/2) ); 	
			}
			else {				## Haldane function
				$theta=sprintf("%7.6f",((1-exp(-(2 * $diff/100))) / 2)); 
			}
			if ($theta == 0) {$theta= 0.000001; print "$z[2] theta eq 0, inserted small distance 0.000001\n";}
			push (@recomb_list," $theta");
			push (@ghuse,"$diff $z[2]");
		}
		$lastpos=$z[1];
	}
	#### QTL begin ####
	if ($qtl_select == 1) {
		for (my $j=1;$j<=$c_traits;$j++) {
			print OUT "0  2   \<\< QUANTITATIVE $qtlname{$j}, NO. OF ALLELES\n";	# default genetic model
			print OUT " $fp $fq  \<\< GENE FREQUENCIES\n";
			print OUT " 1 << NO. OF TRAITS\n";			
			print OUT "     0.000     0.000     0.000 << GENOTYPE MEANS\n";			
			print OUT "     1.000  << VARIANCE - COVARIANCE MATRIX\n";			
			print OUT "     1.000  << MULTIPLIER FOR VARIANCE IN HETEROZYGOTES\n";
			push (@recomb_list," 0.1");
		}
	}
	print OUT " 0 0\n";
	print OUT "@recomb_list\n";
	print OUT " 1      2.0  1.0\n";
	close (OUT);

#-------------------------------gh_setup.in------------------------------###
  if ($selection eq "gh") {
	open (OUT,"> $targetdir/$chr_dir/$setupfile") || die "could not open setupfile $setupfile :$!\n";
	print OUT "photo gh_$vnr.out\n";
	if ($mapfunc eq "Kosambi") {print OUT "map kosambi\n";} # map func
	if ($gh_imp == 1) {print OUT "imprinting on\n";}		
	print OUT "load markers $datfile\n";
	print OUT "use\n";
	print OUT "# @ghuse \n"; 		# for manual marker selection
	print OUT "ps off\n";
	if ($gh_sp == 1) {print OUT "single point on\n";}
	print OUT "score $gh_score\n";
	print OUT "increment step $gh_step\n";
	print OUT "max bits $gh_mb\n";
	if ($gh_ps1 == 1) {print OUT "ps on\n";}
	if ($gh_haplo == 1) {print OUT "haplo on\n";} else {print OUT "haplo off\n";}
	if ($gh_cr == 1) {print OUT "count recs on\n";} else {print OUT "count recs off\n";}
	if ($gh_dis == 1) {print OUT "discard on\n";} else {print OUT "discard off\n";}
	if ($gh_offend eq "") {print OUT "off end\n";} else {print OUT "off end $gh_offend\n";}
	if ($gh_mod == 1) {print OUT "modcalc single\n";}		
#	if ($gh_mod == 0) {print OUT "compute sharing on\n";}		
	if ($gh_displ == 0) {print OUT "display scores off\n";}

	print OUT "scan $pedfile\n";
	if ($gh_ps1 == 1) {print OUT "fam_$vnr.ps\n";}
	print OUT "\n\n\n\n\n\n\n\n\n\n\n\n"; # for each family 1x return if "haplo on" and "ps on"

	print OUT "display scores on\n";
	if ($gh_ps2 == 1) {print OUT "ps on\n";} else {print OUT "ps off\n";}

	if ($gh_tsh == 1) {
		print OUT "total stat het\n";
		print OUT "npl_plot_$vnr.ps\n";
		print OUT "lod_plot_$vnr.ps\n";
		print OUT "info_content_$vnr.ps\n";
	}
	if ($gh_mod == 1) {
		print OUT "display scores off\n";
		print OUT "modscore\n";
		print OUT "modscore_results_$vnr.ps\n\n\n";
		print OUT "display scores on\n";
		print OUT "total stat het\n";
		print OUT "mod_npl_plot_$vnr.ps\n";
		print OUT "mod_lod_plot_$vnr.ps\n";
		print OUT "mod_info_content_$vnr.ps\n";
	}
	print OUT "\n\n\n";
	if ($gh_tdt2==1){$gh_tdt=1;}
	if ($gh_tdt==1) {print OUT "photo tdt_${vnr}.${lastchrom}\ntdt $pedfile\n";}
	if ($gh_tdt2==1) {print OUT "photo tdt2_${vnr}.${lastchrom}\ntdt2\n";}
	print OUT "\n\nq\n";
	close (OUT);
  }
}	# end PrintSubsetFiles

###############  D E L E T E   U N L I K E L Y  G E N O T Y P E S  #############
#
# Merlin option "--error" produces the errorfile "merlin.err"
# merlin.err from all chromosomes should be copied together to "unlikely.all"
#
sub DelUnlikely {

	if (! -f "unlikely.all") { ShowOutput("unlikely.all not found: no deletion of unlikely genotypes\n");}
	else {
		my %unlike=();	# number of unlikely entries for each snps
		my $c_del=0;
		open (IN,"unlikely.all") || die "could not open unlikely.all :$!\n";
		while (<IN>){
			next if /^$/;
			next if /FAM/;
			chomp;
			my @v=split(' ',$_);
			if ($v[3] < $del_unl_th) {
#				print "$v[0]\t$v[1]\t$v[2]\t$v[3]\n";
				$unlike{$v[2]}++;
				if (exists $gtype{$v[1]}{$v[2]}) {
					delete ($gtype{$v[1]}{$v[2]});
					$c_del++;
				}
			}
		}
		close (IN);
		my $num=(keys %unlike);
		print "$num SNPs have unlikely genotypes lower than threshold $del_unl_th\n";
		print "$c_del entries in hash genotypes deleted\n";
		ShowOutput("$num SNPs have unlikely genotypes lower than threshold $del_unl_th\n");
		ShowOutput("$c_del genotypes deleted\n");
		
	}
}

###############  D E L E T E    M E N D E L I A N  E R R O R S  #############
#
# Deletes mendelian errors in the families where they appear
# Errors are stored in a file "pedcheck.all" by PedCheck (button)
#
sub DelErrors {
	my $snp="";
	my $fam="";
	my $ind="";
	my $c_del="";
	
	&ReadPedCheckErr;
	print "Delete mendelian errors in families\n";
	foreach $fam (keys %err) {
		for $snp (keys %{$err{$fam}}) {
			foreach $ind (@{$member{$fam}}) {
				if ($gtype{$ind}{$snp}) {
					delete ($gtype{$ind}{$snp});
					$c_del++;
				}
			}			
		}
	}
	print "$c_del genotypes deleted\n\n";
	ShowOutput("$c_del genotypes in families with mendelian errors deleted\n");
	
}

######################   F I L E  S T A T I S T I K    #########################
sub CallingRate {	# counts genotypes and do some statictics
	if ($statusdata == 0) {
		Errormsg("No data loaded!\nPlease enter genotypefile and read files!\n");
		return;
	}
	my %c_SNP=();
	@allhomozygote=();
	%allhomoz=();
	my %nocall=();
	my $c_nocalls=0;
	my $calls=0;
	my $rate=0.0;
	print "Calculate CallingRate\n";
	open (OUT,"> $statfile") || die "could not open $statfile :$!\n";
	print OUT ("$header\n");
	my $sum=0;
	foreach (@data) {			# fr jeden SNP
		my @v=split('\t',$_);
		my $nc=0;
		my $AA=0;
		my $BB=0;
		$sum++;

		for (my $z=1;$z<=$#head;$z++) 	{	# fr jede Person
			if ($v[$z] eq "NC") {$nc++;$nocall{$sample{$z}}++;}
			if (($v[$z] eq "NC")||($v[$z] eq "AA")||($v[$z] eq "A")) {$AA++;}
			if (($v[$z] eq "NC")||($v[$z] eq "BB")||($v[$z] eq "B")) {$BB++;}
		}


		$c_SNP{$nc}++;
		$c_nocalls+=$nc;
		if ($nc == $#head){push (@allhomozygote,$v[0]);next;}
		if ($AA == $#head){push (@allhomozygote,$v[0]);next;}
		if ($BB == $#head){push (@allhomozygote,$v[0]);}
	}

	my $ngtyps=$#head * $sum;	# sum of all genotypes over all samples and all genotyped SNPs
	my $proz=sprintf("%5.2f",($ngtyps-$c_nocalls)*100/$ngtyps);
	ShowOutput("Callrate over all: \(${proz}\%\) of $ngtyps genotypes\n");	
	print OUT "Callrate over all: \(${proz}\%\) of $ngtyps genotypes\n";


	for (my $i=$#head;$i >= 0;$i--) {
# 		ShowOutput("SNPs with $i NoCalls: $c_SNP{$i}\n");
		print OUT "SNPs with $i NoCalls: $c_SNP{$i}\n";
	}
	my $var=$#allhomozygote + 1;
	print OUT "\nSNPs not informative : $var\n";
	print OUT "\ntogether $c_nocalls NoCalls\n";

	ShowOutput("\nSNPs not informative : $var\n");

	print OUT "\nCalling Rate by sample:\n";
	for (my $z=1;$z<=$#head;$z++) 	{		# for each sample
		$calls=$sum-$nocall{$sample{$z}};
		$rate=sprintf("%5.3f",$calls/$sum);
		print OUT "Calls sample $sample{$z} : $calls \($rate\) of $sum\n";
	}

	ShowOutput("\nCalculate calling rate done\n");
	close (OUT);
	print " Calculate calling rate done\n\n";

	foreach my $n (@allhomozygote) {
		$allhomoz{$n}=1;
	}

	$statusstat=1;
}

####################   A L L E L E   F R E Q U E N C I E S    ##################
sub CalcAllFreq {

	if ($statusdata == 0) {
		ShowOutput("No data loaded!\nPlease enter genotypefile and read files!\n");
		return;
	}

	my @liste=();
	my $minor =0; 
	my ($anzA, $anzB, $sum, $AA, $AB, $BB, $NC, $freqA, $freqB);
	my $notinf=0; 
	my $hetexp=0;
	my $hetobs=0;
	push (@liste, @autolist,@nokoordlist);
	my $var=$#liste+1;
	my $NA=0;
	my @gsamples=();	# selected and genotyped samples

	###--- select samples ---###	
	if ($sample_set eq "all individuals") {
		foreach my $pid (keys %indiv) {	### how much individuals are genotyped? ###
			if (exists $samples{$pid}){
				push (@gsamples,$pid);	# select only genotyped individuals
			}
		}
	}
	elsif ($sample_set eq "unaffected founders") {
		foreach my $pid (@unaffounder) {	# how much unaffected founders are genotyped?
			if (exists $samples{$pid}){
				push (@gsamples,$pid);	# select only genotyped unaffected founders
			}
		}
	}
	elsif ($sample_set eq "affected non-founders") { # @affnonfounder
		foreach my $pid (@affnonfounder) {	# how much affected non-founders are genotyped?
			if (exists $samples{$pid}){
				push (@gsamples,$pid);	# select only genotyped affected non-founders
			}
		}
	}
	elsif ($sample_set eq "founders only") { # @founder
		foreach my $pid (@founder) {	# how much founders are genotyped?
			if (exists $samples{$pid}){
				push (@gsamples,$pid);	# select only genotyped affected non-founders
			}
		}
	}
	else {
		foreach my $pid (@founder) {	# how much founders are genotyped?
			if (exists $samples{$pid}){
				push (@gsamples,$pid);	# select only genotyped unaffected founders
			}
		}
	}
		
	my $gf=$#gsamples +1;
	print "Calculate allele frequencies from $gf $sample_set in pedfile\n";
	print " autosomal\t$var marker\n";
	ShowOutput("\nCalculate allele frequencies from $sample_set\n");
	ShowOutput(" genotyped\t$gf\n");	
	ShowOutput(" autosomal\t$var marker\n");	

	ShowOutput("\nGenotyped samples:\n");	
	foreach my $pid (@gsamples) {
		ShowOutput(" $pid");
	}
	ShowOutput("\n");	
	
		

	$frqfile="alleles_${sample_set}.frq";
	$frqfile =~ s/ /_/g;
	
	open (OUT,"> $frqfile") || die "could not open $frqfile :$!\n";
	print OUT ("#snpname\tfreqA\tfreqB\tminor\tHETexp\tHETobs\tAA\tAB\tBB\tNoCalls\tCalls\tCallrate\tHWE_Chi^2\n");
	##----- autosomal-----##

	foreach my $snp (@liste) {
		$AA=0; $BB=0; $AB=0; $NC=0;
		foreach my $pid (@gsamples) {
			if ($gtype{$pid}{$snp} eq "AA") {$AA++;}
			elsif ($gtype{$pid}{$snp} eq "BB") {$BB++;}
			elsif ($gtype{$pid}{$snp} eq "AB") {$AB++;}
			else {$NC++;}
		}
		
		$anzA=((2*$AA) + $AB);
		$anzB=((2*$BB) + $AB);
		$sum=$anzA+$anzB;
		my $calls=$AA + $AB + $BB;
		my $rate=$calls/$gf;
		if ($sum > 0.) {
			$freqA=sprintf("%5.3f",($anzA/$sum));
			$freqB=1-$freqA;
			if (($anzA==0)||($anzB==0)) {$notinf++;}
			if ($freqA < $freqB) {$minor = $freqA} else {$minor =$freqB;}
			$hetobs=sprintf("%5.3f",$AB/($AA + $AB + $BB));
			$hetexp=(2*$freqA*$freqB);
			my $chi2=Hwe($AA,$AB,$BB);
			printf OUT ("%-10s\t%5.3f\t%5.3f\t%5.3f\t%5.3f\t%5.3f\t%3d\t%3d\t%3d\t%3d\t%4d\t%4.3f\t%s\n",$snp,$freqA,$freqB,$minor,$hetexp,$hetobs,$AA,$AB,$BB,$NC,$calls,$rate,$chi2);
		}
		else {$NA++;
			printf OUT ("%-10s\t----\t----\t----\t----\t----\t%3d\t%3d\t%3d\t%3d\t%4d\t%4.3f\t----\n",$snp,$AA,$AB,$BB,$NC,$calls,$rate);
		}
	}

	##----- x-linked -----##
	@liste=();
	push (@liste, @xlist);
	$var=$#liste+1;
	print " x-linked\t$var marker\n";	
	ShowOutput(" x-linked\t$var marker\n");
	
	foreach my $snp (@liste) {
		$AA=0; $BB=0; $AB=0; $NC=0; $anzA=0; $anzB=0;
		foreach my $pid (@gsamples) {
			if ($gender{$pid} eq "2") {
				
				if ($gtype{$pid}{$snp} eq "AA") {$AA++;}
				elsif ($gtype{$pid}{$snp} eq "BB") {$BB++;}
				elsif ($gtype{$pid}{$snp} eq "AB") {$AB++;}
				else {$NC++;}
			}
		}
		$anzA=((2*$AA) + $AB);
		$anzB=((2*$BB) + $AB);

		$sum=$anzA+$anzB;
		$gf = $AA + $AB + $BB + $NC;	# genotyped female
		my $calls=$AA + $AB + $BB;
		my $rate=($AA + $AB + $BB)/$gf;
		if ($sum > 0.) {
			$freqA=sprintf("%5.3f",($anzA/$sum));
			$freqB=1-$freqA;
			if (($anzA==0)||($anzB==0)) {$notinf++;}
			if ($freqA < $freqB) {$minor = $freqA} else {$minor =$freqB;}
			$hetobs=sprintf("%5.3f",$AB/($AA + $AB + $BB));
			$hetexp=(2*$freqA*$freqB);
			my $chi2=Hwe($AA,$AB,$BB);
			printf OUT ("%-10s\t%5.3f\t%5.3f\t%5.3f\t%5.3f\t%5.3f\t%3d\t%3d\t%3d\t%3d\t%4d\t%4.3f\t%s\n",$snp,$freqA,$freqB,$minor,$hetexp,$hetobs,$AA,$AB,$BB,$NC,$calls,$rate,$chi2);
		}
		else {$NA++;printf OUT ("%-10s\t----\t----\t----\t----\t----\t%3d\t%3d\t%3d\t%3d\t%4d\t%4.3f\t----\n",$snp,$AA,$AB,$BB,$NC,$calls,$rate);}
	}	
	##----- end x-linked -----##

	close (OUT);
	if ($NA > 0) { print " no genotypes available in $NA markers\n"; }
	print " non-informative $notinf markers\n write file: $frqfile\n\n";
	print "Done\n";
	if ($NA > 0) { ShowOutput(" no genotypes available in $NA markers\n write file: $frqfile\n"); }
	ShowOutput(" write file: $frqfile\n");
	ShowOutput("Done\n");
	
}


#########################   Merlin unlikely errors     ################################
sub CreMerlinErrList {
	my $dir="";
	my $errfile="";
	if ($command_line == 1) {
		$errfile="merlin/c01/merlin.err";
	}
	else {
		$errfile=FileDialog("Please point to one merlin.err file!");
	}

	my @v=split('\/',$errfile);
	for (my $i=0;$i<$#v-1;$i++){
		$dir .= "$v[$i]/";
	}
	print "Merlin dir: $dir\n";
	if ($dir eq "") {print "No File selected\n"; return;}
	open (OUT, "> unlikely.all") || die "could not open unlikely.all  :$!\n";
	print OUT "    FAMILY     PERSON     MARKER      RATIO\n";

	foreach my $i ('01','02','03','04','05','06','07','08','09',10,11,12,13,14,15,16,17,18,19,20,21,22,23,24) {
		$errfile="${dir}c${i}/merlin.err";
		print "$errfile\n";
		if (-f $errfile) {
			open (IN, "$errfile") || die "could not open merlin.err $errfile :$!\n";
			while (<IN>){
				next if /^$/;		# skip blank line
				next if /FAM/;	# skip header line
				print OUT "$_";
			}
			close (IN);
		}
		else {print "no $errfile\n";}
	}
	close (OUT);
	print "Write file: $work_dir/unlikely.all\n";
	ShowOutput("\nFile unlikely.all created\n");
	
}


##################################  S U B s  ##################################
sub LoadEnv {
	open (fhin, "$saveenv") || die "could not open $saveenv :$!\n";
	print "Read $saveenv\n";
#	ShowOutput("Read $saveenv\n");
	while (<fhin>){
		next if /^$/;
		next if /^\*/;
		next if /^\#/;
		my @v = split(' ',$_);
		my @z = split('\=',$v[0]);
		if    ($z[0] eq "fq") {$fq=$z[1];$fp=(1-$fq);}
		elsif ($z[0] eq "pvf1") {$pvf1=$z[1];}
		elsif ($z[0] eq "pvf2") {$pvf2=$z[1];}
		elsif ($z[0] eq "pvf3") {$pvf3=$z[1];}
		elsif ($z[0] eq "pvf4") {$pvf4=$z[1];}
		elsif ($z[0] eq "gh_ps1") {$gh_ps1=$z[1];}
		elsif ($z[0] eq "gh_ps2") {$gh_ps2=$z[1];}
		elsif ($z[0] eq "gh_sp") {$gh_sp=$z[1];}
		elsif ($z[0] eq "gh_haplo") {$gh_haplo=$z[1];}
		elsif ($z[0] eq "gh_cr") {$gh_cr=$z[1];}
		elsif ($z[0] eq "gh_dis") {$gh_dis=$z[1];}
		elsif ($z[0] eq "gh_displ") {$gh_displ=$z[1];}
		elsif ($z[0] eq "gh_tsh") {$gh_tsh=$z[1];}
		elsif ($z[0] eq "gh_tdt") {$gh_tdt=$z[1];}
		elsif ($z[0] eq "gh_tdt2") {$gh_tdt2=$z[1];}
		elsif ($z[0] eq "gh_mb") {$gh_mb=$z[1];}
		elsif ($z[0] eq "gh_step") {$gh_step=$z[1];}
		elsif ($z[0] eq "gh_prog") {$gh_prog=$z[1];}
		elsif ($z[0] eq "gh_imp") {$gh_imp=$z[1];}
		elsif ($z[0] eq "gh_mod") {$gh_mod=$z[1];}
		elsif ($z[0] eq "gh_score") {$gh_score=$z[1];}
		elsif ($z[0] eq "chip") {$chip=$z[1];}
		elsif ($z[0] eq "map") {$genmap=$z[1];}
		elsif ($z[0] eq "genotype_file") {$infile=$z[1];}
		elsif ($z[0] eq "pedfile_pro") {$pedfilepro=$z[1];}
		elsif ($z[0] eq "skip_nopos") {$skip_nopos=$z[1];}
		elsif ($z[0] eq "skip_errors") {$skip_errors=$z[1];}
		elsif ($z[0] eq "skip_list") {$skip_list=$z[1];}
		elsif ($z[0] eq "skip_notinf") {$skip_notinf=$z[1];}
		elsif ($z[0] eq "del_errors") {$del_errors=$z[1];}
		elsif ($z[0] eq "del_unlikely") {$del_unlikely=$z[1];}
		elsif ($z[0] eq "del_unl_th") {$del_unl_th=$z[1];}
		elsif ($z[0] eq "allele_freq") {$allfreq=$z[1];}
		elsif ($z[0] eq "map_func") {$mapfunc=$z[1];}
		elsif ($z[0] eq "qtl_select") {$qtl_select=$z[1];}
		elsif ($z[0] eq "qtl_file") {$qtlfile=$z[1];}
		elsif ($z[0] eq "alias_name") {$aliasname=$z[1];}
		elsif ($z[0] eq "genotype_file") {$infile=$z[1];}
		elsif ($z[0] eq "pedfile_pro") {$pedfilepro=$z[1];}
		elsif ($z[0] eq "skiplist_file") {$skipfile=$z[1];}
		elsif ($z[0] eq "make_subsets") {$subsets=$z[1];}
		elsif ($z[0] eq "max_snp") {$maxsnp=$z[1];}
				
		###--------------- genetic maps  ------------###

		elsif ($z[0] eq "Xba131_map_deCode") {$decode_map_131=$z[1];}
		elsif ($z[0] eq "Xba131_map_Marshf") {$marshf_map_131=$z[1];}
		elsif ($z[0] eq "Xba131_map_SLM1") {$slm1_map_131=$z[1];}
		elsif ($z[0] eq "Xba131_map_Other") {$other_map_131=$z[1];}

		elsif ($z[0] eq "Xba142_map_deCode") {$decode_map_142=$z[1];}
		elsif ($z[0] eq "Xba142_map_Marshf") {$marshf_map_142=$z[1];}
		elsif ($z[0] eq "Xba142_map_SLM1") {$slm1_map_142=$z[1];}
		elsif ($z[0] eq "Xba142_map_Other") {$other_map_142=$z[1];}

		elsif ($z[0] eq "Xba240_map_deCode") {$decode_map_240=$z[1];}
		elsif ($z[0] eq "Xba240_map_Marshf") {$marshf_map_240=$z[1];}
		elsif ($z[0] eq "Xba240_map_SLM1") {$slm1_map_240=$z[1];}
		elsif ($z[0] eq "Xba240_map_Other") {$other_map_240=$z[1];}

		elsif ($z[0] eq "Hind240_map_deCode") {$decode_map_hind=$z[1];}
		elsif ($z[0] eq "Hind240_map_Marshf") {$marshf_map_hind=$z[1];}
		elsif ($z[0] eq "Hind240_map_SLM1") {$slm1_map_hind=$z[1];}
		elsif ($z[0] eq "Hind240_map_Other") {$other_map_hind=$z[1];}

		elsif ($z[0] eq "Nsp_map_deCode") {$decode_map_nsp=$z[1];}
		elsif ($z[0] eq "Nsp_map_Marshf") {$marshf_map_nsp=$z[1];}
		elsif ($z[0] eq "Nsp_map_SLM1") {$slm1_map_nsp=$z[1];}
		elsif ($z[0] eq "Nsp_map_Other") {$other_map_nsp=$z[1];}

		elsif ($z[0] eq "Sty_map_deCode") {$decode_map_sty=$z[1];}
		elsif ($z[0] eq "Sty_map_Marshf") {$marshf_map_sty=$z[1];}
		elsif ($z[0] eq "Sty_map_SLM1") {$slm1_map_sty=$z[1];}
		elsif ($z[0] eq "Sty_map_Other") {$other_map_sty=$z[1];}

		elsif ($z[0] eq "Illumina_map_deCode") {$decode_map_illumi=$z[1];}
		elsif ($z[0] eq "Illumina_map_Marshf") {$marshf_map_illumi=$z[1];}
		elsif ($z[0] eq "Illumina_map_SLM1") {$slm1_map_illumi=$z[1];}
		elsif ($z[0] eq "Illumina_map_Other") {$other_map_illumi=$z[1];}


		###--------------- allele frequency files  --------------###

		elsif ($z[0] eq "Xba131_freqA_afam") {$freq_afam_131=$z[1];}
		elsif ($z[0] eq "Xba131_freqA_asian") {$freq_asian_131=$z[1];}
		elsif ($z[0] eq "Xba131_freqA_caucasian") {$freq_cauc_131=$z[1];}
		elsif ($z[0] eq "Xba131_freqA_Other") {$freq_other_131=$z[1];}

		elsif ($z[0] eq "Xba142_freqA_afam") {$freq_afam_142=$z[1];}
		elsif ($z[0] eq "Xba142_freqA_asian") {$freq_asian_142=$z[1];}
		elsif ($z[0] eq "Xba142_freqA_caucasian") {$freq_cauc_142=$z[1];}
		elsif ($z[0] eq "Xba142_freqA_Other") {$freq_other_142=$z[1];}

		elsif ($z[0] eq "Xba240_freqA_afam") {$freq_afam_240=$z[1];}
		elsif ($z[0] eq "Xba240_freqA_asian") {$freq_asian_240=$z[1];}
		elsif ($z[0] eq "Xba240_freqA_caucasian") {$freq_cauc_240=$z[1];}
		elsif ($z[0] eq "Xba240_freqA_Other") {$freq_other_240=$z[1];}

		elsif ($z[0] eq "Hind240_freqA_afam") {$freq_afam_hind=$z[1];}
		elsif ($z[0] eq "Hind240_freqA_asian") {$freq_asian_hind=$z[1];}
		elsif ($z[0] eq "Hind240_freqA_caucasian") {$freq_cauc_hind=$z[1];}
		elsif ($z[0] eq "Hind240_freqA_Other") {$freq_other_hind=$z[1];}

		elsif ($z[0] eq "Nsp_freqA_afam") {$freq_afam_nsp=$z[1];}
		elsif ($z[0] eq "Nsp_freqA_asian") {$freq_asian_nsp=$z[1];}
		elsif ($z[0] eq "Nsp_freqA_caucasian") {$freq_cauc_nsp=$z[1];}
		elsif ($z[0] eq "Nsp_freqA_Other") {$freq_other_nsp=$z[1];}

 		elsif ($z[0] eq "Sty_freqA_afam") {$freq_afam_sty=$z[1];}
		elsif ($z[0] eq "Sty_freqA_asian") {$freq_asian_sty=$z[1];}
		elsif ($z[0] eq "Sty_freqA_caucasian") {$freq_cauc_sty=$z[1];}
		elsif ($z[0] eq "Sty_freqA_Other") {$freq_other_sty=$z[1];}

 		elsif ($z[0] eq "Illumina_freqA_afam") {$freq_afam_illumi=$z[1];}
		elsif ($z[0] eq "Illumina_freqA_asian") {$freq_asian_illumi=$z[1];}
		elsif ($z[0] eq "Illumina_freqA_caucasian") {$freq_cauc_illumi=$z[1];}
		elsif ($z[0] eq "Illumina_freqA_Other") {$freq_other_illumi=$z[1];}		

		else {print "Skip unknown option $z[0]!\n";}
	}
	close (fhin);
}
####################   S A V E  E N V I R O N M E N T    #######################
sub SaveCurrEnv {	# Save genetic model and variables
	open (OUT,"> $saveenv") || die "could not open $saveenv :$!\n";
	print OUT "### Main locus mutant allele frequency ###\n";
	print OUT "fq\=$fq\n";
	print OUT "\n### Penetrance vector normal: pvf1(++) pvf2(+-) pvf3(--) ###\n";
	print OUT "### Penetrance vector GH_Imprinting: pvf1(++) pvf2(-+)(paternal) pvf3(+-)(maternal) pvf4(--) ###\n";
	print OUT "pvf1\=$pvf1\n";
	print OUT "pvf2\=$pvf2\n";
	print OUT "pvf3\=$pvf3\n";
	print OUT "pvf4\=$pvf4\n";
	print OUT "\n### Genehunter Options (1-on, 0-off) ###\n";
	print OUT "gh_ps1\=$gh_ps1	\# postscript for family haplotypes\n";
	print OUT "gh_ps2\=$gh_ps2	\# postscript of LOD-, NPL-scores and Inform. Content in total stat het\n";
	print OUT "gh_sp\=$gh_sp 	\# single point\n";
	print OUT "gh_haplo\=$gh_haplo	\# haplotyping\n";
	print OUT "gh_cr\=$gh_cr 	\# count recs\n";
	print OUT "gh_dis\=$gh_dis	\# discard\n";
	print OUT "gh_displ\=$gh_displ	\# display scores \(family\)\n";
	print OUT "gh_tsh\=$gh_tsh	\# total stat het\n";
	print OUT "gh_tdt\=$gh_tdt	\# TDT\n";
	print OUT "gh_tdt2\=$gh_tdt2	\# TDT2\n";
	print OUT "gh_mb\=$gh_mb	\# max bits\n";
	print OUT "gh_step\=$gh_step	\# increment step\n";
	print OUT "gh_prog\=$gh_prog	\# name of genehunter program\n";
	print OUT "gh_imp\=$gh_imp	\# imprinting\n";
	print OUT "gh_mod\=$gh_mod	\# modscore\n";
	print OUT "gh_score\=$gh_score	\# scoring function: all \| pairs \| hom\n";

	print OUT "\n### Other Options ###\n";
	print OUT "chip\=$chip		\# chip type (enzyme)\n";
	print OUT "map\=$genmap		\# genetic map\n";
	print OUT "skip_nopos\=$skip_nopos		\# skip SNPs w\/o position\n";
	print OUT "skip_errors\=$skip_errors		\# skip SNPs with mendelian errors\n";
	print OUT "skip_notinf\=$skip_notinf		\# skip SNPs not informative in all samples in all families\n";
	print OUT "skip_list\=$skip_list		\# use list with markers to omit\n";
	print OUT "del_errors\=$del_errors		\# delete Mendelian errors in families\n";
	print OUT "del_unlikely\=$del_unlikely		\# delete Merlin unlikely genotypes \n";
	print OUT "del_unl_th\=$del_unl_th		\# delete unlikely genotypes < threshold\n";
	print OUT "allele_freq\=$allfreq	\# allele frequency\n";
	print OUT "map_func\=$mapfunc	\# map function\n";
	print OUT "qtl_select\=$qtl_select	\# QTL selection\n";
	print OUT "qtl_file\=$qtlfile	\# QTL file\n";
	print OUT "alias_name\=$aliasname	\# use SNP alias name\n";
	print OUT "make_subsets\=$subsets	\# create moving window\n";
	print OUT "max_snp\=$maxsnp	\# number of marker in a window\n";

	
	print OUT "\n###------- File Options -------###\n";
	print OUT "genotype_file\=$infile		\# file containing genotype data\n";
	print OUT "pedfile_pro\=$pedfilepro		\# file containing pedigree structue and affection status\n";
	print OUT "skiplist_file\=$skipfile		\# file containing SNPs to omit \(completely\)\n";

	###----------------- genetic maps  ----------------###
	print OUT "\n###---- genetic map files -----###\n";
	print OUT "Xba131_map_deCode\=$decode_map_131	\# Xba131 10K\n";
	print OUT "Xba131_map_Marshf\=$marshf_map_131\n";
	print OUT "Xba131_map_SLM1\=$slm1_map_131\n";
	print OUT "Xba131_map_Other\=$other_map_131\n";

	print OUT "Xba142_map_deCode\=$decode_map_142	\# Xba142 10Kv2\n";
	print OUT "Xba142_map_Marshf\=$marshf_map_142\n";
	print OUT "Xba142_map_SLM1\=$slm1_map_142\n";
	print OUT "Xba142_map_Other\=$other_map_142\n";

	print OUT "Xba240_map_deCode\=$decode_map_240	\# Xba240 50K\n";
	print OUT "Xba240_map_Marshf\=$marshf_map_240\n";
	print OUT "Xba240_map_SLM1\=$slm1_map_240\n";
	print OUT "Xba240_map_Other\=$other_map_240\n";

	print OUT "Hind240_map_deCode\=$decode_map_hind	\# Hind240 50K\n";
	print OUT "Hind240_map_Marshf\=$marshf_map_hind\n";
	print OUT "Hind240_map_SLM1\=$slm1_map_hind\n";
	print OUT "Hind240_map_Other\=$other_map_hind\n";

	print OUT "Nsp_map_deCode\=$decode_map_nsp	\# Nsp 250K \n";
	print OUT "Nsp_map_Marshf\=$marshf_map_nsp\n";
	print OUT "Nsp_map_SLM1\=$slm1_map_nsp\n";
	print OUT "Nsp_map_Other\=$other_map_nsp\n";

	print OUT "Sty_map_deCode\=$decode_map_sty	\# Sty 250K\n";
	print OUT "Sty_map_Marshf\=$marshf_map_sty\n";
	print OUT "Sty_map_SLM1\=$slm1_map_sty\n";
	print OUT "Sty_map_Other\=$other_map_sty\n";

	print OUT "Illumina_map_deCode\=$decode_map_illumi	\# Illumina 6K\n";
	print OUT "Illumina_map_Marshf\=$marshf_map_illumi\n";
	print OUT "Illumina_map_SLM1\=$slm1_map_illumi\n";
	print OUT "Illumina_map_Other\=$other_map_illumi\n";
	
	###--------------- allele frequency files  --------------###
	print OUT "\n###---- allele frequency files ----###\n\n";

	print OUT "Xba131_freqA_afam\=$freq_afam_131\n";
	print OUT "Xba131_freqA_asian\=$freq_asian_131\n";
	print OUT "Xba131_freqA_caucasian\=$freq_cauc_131\n";
	print OUT "Xba131_freqA_Other\=$freq_other_131\n";

	print OUT "Xba142_freqA_afam\=$freq_afam_142\n";
	print OUT "Xba142_freqA_asian\=$freq_asian_142\n";
	print OUT "Xba142_freqA_caucasian\=$freq_cauc_142\n";
	print OUT "Xba142_freqA_Other\=$freq_other_142\n";

	print OUT "Xba240_freqA_afam\=$freq_afam_240\n";
	print OUT "Xba240_freqA_asian\=$freq_asian_240\n";
	print OUT "Xba240_freqA_caucasian\=$freq_cauc_240\n";
	print OUT "Xba240_freqA_Other\=$freq_other_240\n";

	print OUT "Hind240_freqA_afam\=$freq_afam_hind\n";
	print OUT "Hind240_freqA_asian\=$freq_asian_hind\n";
	print OUT "Hind240_freqA_caucasian\=$freq_cauc_hind\n";
	print OUT "Hind240_freqA_Other\=$freq_other_hind\n";

	print OUT "Nsp_freqA_afam\=$freq_afam_nsp\n";
	print OUT "Nsp_freqA_asian\=$freq_asian_nsp\n";
	print OUT "Nsp_freqA_caucasian\=$freq_cauc_nsp\n";
	print OUT "Nsp_freqA_Other\=$freq_other_nsp\n";

	print OUT "Sty_freqA_afam\=$freq_afam_sty\n";
	print OUT "Sty_freqA_asian\=$freq_asian_sty\n";
	print OUT "Sty_freqA_caucasian\=$freq_cauc_sty\n";
	print OUT "Sty_freqA_Other\=$freq_other_sty\n";

	print OUT "Illumina_freqA_afam\=$freq_afam_illumi\n";
	print OUT "Illumina_freqA_asian\=$freq_asian_illumi\n";
	print OUT "Illumina_freqA_caucasian\=$freq_cauc_illumi\n";
	print OUT "Illumina_freqA_Other\=$freq_other_illumi\n";

	close (OUT);
	ShowOutput("\nEnvironment variables saved in $saveenv\n");
	
}

###################################   H W E   ##################################
sub Hwe {	# Hardy Weinberg Equilibrium Test
	my $notinf=0;
	my ($AA,$AB,$BB,$hwe_chi,@rest);
	my ($eAA,$eAB,$eBB);
	
	($AA,$AB,$BB,@rest)=@_;
	my $N = $AA + $AB + $BB;
	my $anzA=((2*$AA) + $AB);
	my $anzB=((2*$BB) + $AB);
	my $sum=$anzA+$anzB;
	if ($sum > 0.) {
		my $freqA=sprintf("%8.6f",($anzA/$sum));
		my $freqB=1-$freqA;
		if (($anzA==0)||($anzB==0)) {$notinf=1;$hwe_chi="NA";}
		else {
			$eAA=$freqA*$freqA*$N;	# expected AA
			$eAB=2*$freqA*$freqB*$N;
			$eBB=$freqB*$freqB*$N;
			$hwe_chi = sprintf("%6.4f",(($AA-$eAA)**2/$eAA)+ (($AB-$eAB)**2/$eAB)+ (($BB-$eBB)**2/$eBB));	
		}
	}
	return ($hwe_chi);
}

################################   C L E A N    ################################
sub CleanFiles {	# Textbox
	print "delete temporary files!\n\n";
	unlink ('myplot.gp', 'counts.plt','chr_line.plt','chr_line','errors.srt','names.dat', 'pedcheck.err','pedfile.dat');
}


################################   C L E A R    ################################
sub ClearWindow {	# Textbox
	$tb->delete("1.0","end");
	$statusdata=0;
	$statusped=0;
	$statuschk=0;
	$statusmap=0;
	$statusstat=0;
	$statusfreq=0;
	$status_skiplist=0;	# skiplist is loaded = 1
	$status_PedCheckErr=0;	# mendelian errors (pedcheck.all) loaded = 1	@alog=();
}

############################  S H O W   O U T P U T  ###########################
sub ShowOutput {
	if ($command_line == 0) {
		foreach (@_) {
			$tb->insert('end',$_);
		}
		$tb->see('end');
		$tb->update();
	}
	push (@alog,@_);
}

##############################  E R R O R M S G  ###############################

sub Errormsg
{
 my $MW2=MainWindow->new();
 $MW2->title("STATUS:");
 $MW2->Label(-text=>"@_",-width=>60,-height=>10)->pack;
 $MW2->Button(-text=>"OK",
             -width=>38,-height=>1,-command=>sub{destroy $MW2;})->pack;
 MainLoop();
}
#################################  A B O U T  ##################################

sub About
{
 my $MW2=MainWindow->new();
 $MW2->title("About ALOHOMORA $version");
 $MW2->Label(-text=>"ALOHOMORA $version\n\nOPENS THE DOOR\nfrom SNP Array to Linkage Analysis\n\nSNP Array Quality Control and Data Conversion\n\n(c) 2003-2009 Franz Rschendorf\n\nMax-Delbrck-Center for Molecular Medicine, Berlin",-width=>60,-height=>10)->pack;
 $MW2->Button(-text=>"OK",
             -width=>8,-height=>1,-command=>sub{destroy $MW2;})->pack;
 MainLoop();
}

######################  M W 2  L I N K A G E  F I L E S  #######################

sub MW2LinkageFiles {
 
 my $MW2=MainWindow->new();
 $MW2->title("Create Linkage Format Files");
 my $f0 = $MW2->Frame->pack(-side=>'left',-fill=>'x'); 
 my $f1 = $MW2->Frame->pack(-side=>'top',-fill=>'x');
 my $f2 = $MW2->Frame->pack(-side=>'top',-fill=>'x');
 my $f3 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 
 my $f4 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 
 my $f5 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 
 my $f6 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 
 my $f7 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 
 my $f8 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 
 my $f9 = $MW2->Frame->pack(-side=>'top',-fill=>'x');
 my $f10 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 
 my $f11 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 
 my $f12 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 
 my $f13 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 
 my $f14 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 
 my $f19 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 
 my $f20 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 

 $f1->Label(-text => "Genetic Model",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'w');

 $f1->Label(-text => "main locus frequencies",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'top', -anchor =>'nw');

 $f1->Label(-text => "wildtype",-font=>'Arial 10 normal')->pack(-side =>'left', -anchor =>'w');
 my $e1=$f1->Entry(-width=>6, -textvariable=> \$fp)->pack(-side => 'left',-anchor =>'w');
 $f1->Label(-text => "mutant",-font=>'Arial 10 normal')->pack(-side =>'left', -anchor =>'w');
 my $e2=$f1->Entry(-width=>6, -textvariable=> \$fq)->pack(-side => 'left',-anchor =>'w');

 $f3->Label(-text => "penetrance vector",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'top', -anchor =>'nw');
  $f3->Label(-text => "f1",-font=>'Arial 10 normal')->pack(-side =>'left', -anchor =>'w');
 my $e3=$f3->Entry(-width=>6, -textvariable=> \$pvf1)->pack(-side => 'left',-anchor =>'w');
 $f3->Label(-text => "f2",-font=>'Arial 10 normal')->pack(-side =>'left', -anchor =>'w');
 my $e4=$f3->Entry(-width=>6, -textvariable=> \$pvf2)->pack(-side => 'left',-anchor =>'w');
 $f3->Label(-text => "f3",-font=>'Arial 10 normal')->pack(-side =>'left', -anchor =>'w');
 my $e5=$f3->Entry(-width=>6, -textvariable=> \$pvf3)->pack(-side => 'left',-anchor =>'w');
 my $lb_f3="";

 $f4->Label(-text => "\nMoving Window",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'w');
 my $e6=$f4->Entry(-width=>6, -background=>'grey', -state =>'disabled', -textvariable=> \$maxsnp)->pack(-side => 'right',-anchor =>'e');
 my $cb1=$f4->Checkbutton(-text 	=> "Make Subsets",
						-variable => \$subsets,
						-command=>sub{if($subsets==1){$e6->configure(-background=>'white',-state =>'normal')}
									else {$e6->configure(-background=>'grey',-state =>'disabled')}})-> pack(-side => 'left',-anchor =>'nw');

 if (lc($selection) eq "gh") {

	$f5->Label(-text => "\nGenehunter Options",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'w');
	my $e1_f5=$f5->Entry(-width=>6, -textvariable=> \$gh_prog)->pack(-side => 'right',-anchor =>'e');								
	my $lb1_f5=$f5->Label(-text => "program name")->pack(-side =>'left', -anchor =>'w');
	
	my $cb2=$f6->Checkbutton(-text 	=> "postscript haplotyping",
						-variable => \$gh_ps1)-> pack(-side => 'top',-anchor =>'nw');
	my $cb3=$f6->Checkbutton(-text 	=> "single point",
						-variable => \$gh_sp)-> pack(-side => 'top',-anchor =>'nw');
	my $cb4=$f6->Checkbutton(-text 	=> "haplotyping",
						-variable => \$gh_haplo)-> pack(-side => 'top',-anchor =>'nw');
	my $cb5=$f6->Checkbutton(-text 	=> "count recs",
						-variable => \$gh_cr)-> pack(-side => 'top',-anchor =>'nw');
	my $cb6=$f6->Checkbutton(-text 	=> "discard",
						-variable => \$gh_dis)-> pack(-side => 'top',-anchor =>'nw');
	my $cb20=$f6->Checkbutton(-text 	=> "display scores (family)",
						-variable => \$gh_displ)-> pack(-side => 'top',-anchor =>'nw');
	my $cb7=$f6->Checkbutton(-text 	=> "postscript total stat",
						-variable => \$gh_ps2)-> pack(-side => 'top',-anchor =>'nw');
	my $cb8=$f6->Checkbutton(-text 	=> "total stat het",
						-variable => \$gh_tsh)-> pack(-side => 'top',-anchor =>'nw');
	my $cb9=$f6->Checkbutton(-text 	=> "Modscore",
						-variable => \$gh_mod)-> pack(-side => 'top',-anchor =>'nw');


	my $cb10=$f6->Checkbutton(-text 	=> "Imprinting",
		-variable => \$gh_imp,
		-command=>sub{ 
				if(($gh_imp == 1) && ($lb_f3 eq "")) {
		  			$lb_f3=$f3->Label(-text => "f4",-font=>'Arial 10 normal')->pack(-side =>'left', -anchor =>'w');
 		  			my $e6=$f3->Entry(-width=>6, -textvariable=> \$pvf4)->pack(-side => 'left',-anchor =>'w');
 		  		}
 		})-> pack(-side => 'top',-anchor =>'nw');

	my $cb11=$f6->Checkbutton(-text 	=> "TDT",
						-variable => \$gh_tdt)-> pack(-side => 'top',-anchor =>'nw');
	my $cb12=$f6->Checkbutton(-text 	=> "TDT2",
 						-variable => \$gh_tdt2)-> pack(-side => 'top',-anchor =>'nw');
 						
	my $e1_f7=$f7->Entry(-width=>6, -textvariable=> \$gh_mb)->pack(-side => 'right',-anchor =>'e');	
	my $lb1_f7=$f7->Label(-text => "max bits")->pack(-side =>'left', -anchor =>'w');

	my $e1_f8=$f8->Entry(-width=>6, -textvariable=> \$gh_step)->pack(-side => 'right',-anchor =>'e');								
	my $lb1_f8=$f8->Label(-text => "increment step")->pack(-side =>'left', -anchor =>'w');


	my $e1_f10=$f10->Entry(-width=>6, -textvariable=> \$gh_score)->pack(-side => 'right',-anchor =>'e');								
	my $lb1_f10=$f10->Label(-text => "score")->pack(-side =>'left', -anchor =>'w'); 

	my $e1_f11=$f11->Entry(-width=>6, -textvariable=> \$gh_offend)->pack(-side => 'right',-anchor =>'e');								
	my $lb1_f11=$f11->Label(-text => "off end")->pack(-side =>'left', -anchor =>'w');   
  } # end gh options


	my $b1=$f20->Button(-text=>"OK",
             -width=>10,-height=>1,-command=>sub{destroy $MW2;MakeLinkageFiles();})->pack(-side => 'left',-anchor =>'sw');
	my $b2=$f20->Button(-text=>"Cancel",
             -width=>10,-height=>1,-command=>sub{destroy $MW2;})->pack(-side => 'right',-anchor =>'se');
 MainLoop();
}
##################   M A K E   L I N K A G E   F I L E S    ####################

sub MakeLinkageFiles {
	print "Sub Make Linkage files\n";
	
	if ($del_errors == 1) {&DelErrors;}
	if ($del_unlikely == 1) {&DelUnlikely;}
	if (($skip_notinf == 1) && ($statusstat == 0)) { &CallingRate; }	# Skip not informative SNPs

	if ($subsets == 0) {		
		if ($qtl_select == 1) {$targetdir="${selection}_qtl";}
		else {$targetdir=$selection;}
		if (! -d $targetdir) {
			mkdir ($targetdir,0777);
			ShowOutput("Create directory $targetdir\n");
			print "Create directory $targetdir\n";
		}
		else {
			rename ($targetdir,"${targetdir}0");
			mkdir ($targetdir,0777);			
			ShowOutput("\nRename old $targetdir to ${targetdir}0\n");
			print "Rename old $targetdir to ${targetdir}0\n";
			ShowOutput("Create directory $targetdir\n");
			print "Create directory $targetdir\n";
		}
		&MakeNoLimitFiles;
	}
	else {
		$targetdir=$selection."_".$maxsnp;
		if (! -d $targetdir) { 
			mkdir ($targetdir,0777); 
			ShowOutput("Create directory $targetdir\n");
			print "Create directory $targetdir\n";
		}
		else {
			rename ($targetdir,"${targetdir}_0");
			mkdir ($targetdir,0777);			
			ShowOutput("\nRename old $targetdir to ${targetdir}_0\n");
			print "Rename old $targetdir to ${targetdir}_0\n";
			ShowOutput("Create directory $targetdir\n");
			print "Create directory $targetdir\n";
		}
		&MakeSubsetFiles;
	}
}

##################  O P T I O N  F I L E  S E L E C T I O N   ##################

sub FileSelection {
 
 my $MW2=MainWindow->new();
 $MW2->title("Select File Names for $chip");

 my $f5 = $MW2->Frame->pack(-side=>'top',-fill=>'x');
 my $f6 = $MW2->Frame->pack(-side=>'top',-fill=>'x');
 my $f7 = $MW2->Frame->pack(-side=>'top',-fill=>'x');
 my $f8 = $MW2->Frame->pack(-side=>'top',-fill=>'x');
 my $f0 = $MW2->Frame->pack(-side=>'top',-fill=>'x');
 my $f1 = $MW2->Frame->pack(-side=>'top',-fill=>'x');
 my $f2 = $MW2->Frame->pack(-side=>'top',-fill=>'x');
 my $f3 = $MW2->Frame->pack(-side=>'top',-fill=>'x');
 my $f4 = $MW2->Frame->pack(-side=>'top',-fill=>'x'); 
 my $f9 = $MW2->Frame->pack(-side=>'top',-fill=>'x');

 $f0->Label(-text => "\nAllele frequency files for $chip",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'n');

 if ($chip eq "Xba131") {
 $f1->Label(-text => "Afro Americans",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e1=$f1->Entry(-width=>50, -textvariable=> \$freq_afam_131)->pack(-side => 'right');
 my $b1_f1 = $f1->Button(-text => "Browse",
			-command=>sub{$freq_afam_131=FileDialog("Select african american frequency file $chip")})->pack(-side => 'right');

 $f2->Label(-text => "Asians",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e2=$f2->Entry(-width=>50, -textvariable=> \$freq_asian_131)->pack(-side => 'right');
 my $b1_f2 = $f2->Button(-text => "Browse",
			-command=>sub{$freq_asian_131=FileDialog("Select asian frequency file $chip")})->pack(-side => 'right');

 $f3->Label(-text => "Caucasian",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e3=$f3->Entry(-width=>50, -textvariable=> \$freq_cauc_131)->pack(-side => 'right');
 my $b1_f3 = $f3->Button(-text => "Browse",
			-command=>sub{$freq_cauc_131=FileDialog("Select caucasian frequency file $chip")})->pack(-side => 'right');

 $f4->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e4=$f4->Entry(-width=>50, -textvariable=> \$freq_other_131)->pack(-side => 'right');
 my $b1_f4 = $f4->Button(-text => "Browse",
			-command=>sub{$freq_other_131=FileDialog("Select other frequency file $chip")})->pack(-side => 'right');

 $f5->Label(-text => "\nGenetic map files for $chip",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'n');

 $f5->Label(-text => "\nDeCode",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e5=$f5->Entry(-width=>50, -textvariable=> \$decode_map_131)->pack(-side => 'right');
 my $b1_f5 = $f5->Button(-text => "Browse",
			-command=>sub{$decode_map_131=FileDialog("Select DeCode map file $chip ")})->pack(-side => 'right');

 $f6->Label(-text => "Marshfield",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e6=$f6->Entry(-width=>50, -textvariable=> \$marshf_map_131)->pack(-side => 'right');
 my $b1_f6 = $f6->Button(-text => "Browse",
			-command=>sub{$marshf_map_131=FileDialog("Select Marshfield map file $chip")})->pack(-side => 'right');

 $f7->Label(-text => "SLM1",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e7=$f7->Entry(-width=>50, -textvariable=> \$slm1_map_131)->pack(-side => 'right');
 my $b1_f7 = $f7->Button(-text => "Browse",
			-command=>sub{$slm1_map_131=FileDialog("Select SLM1 map file $chip")})->pack(-side => 'right');

 $f8->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e8=$f8->Entry(-width=>50, -textvariable=> \$other_map_131)->pack(-side => 'right');
 my $b1_f8 = $f8->Button(-text => "Browse",
			-command=>sub{$other_map_131=FileDialog("Select other map file $chip")})->pack(-side => 'right');
 }
 elsif ($chip eq "Xba142") {
 $f1->Label(-text => "Afro Americans",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e1=$f1->Entry(-width=>50, -textvariable=> \$freq_afam_142)->pack(-side => 'right');
 my $b1_f1 = $f1->Button(-text => "Browse",
			-command=>sub{$freq_afam_142=FileDialog("Select african american frequency file $chip")})->pack(-side => 'right');

 $f2->Label(-text => "Asians",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e2=$f2->Entry(-width=>50, -textvariable=> \$freq_asian_142)->pack(-side => 'right');
 my $b1_f2 = $f2->Button(-text => "Browse",
			-command=>sub{$freq_asian_142=FileDialog("Select asian frequency file $chip")})->pack(-side => 'right');

 $f3->Label(-text => "Caucasian",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e3=$f3->Entry(-width=>50, -textvariable=> \$freq_cauc_142)->pack(-side => 'right');
 my $b1_f3 = $f3->Button(-text => "Browse",
			-command=>sub{$freq_cauc_142=FileDialog("Select caucasian frequency file $chip")})->pack(-side => 'right');

 $f4->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e4=$f4->Entry(-width=>50, -textvariable=> \$freq_other_142)->pack(-side => 'right');
 my $b1_f4 = $f4->Button(-text => "Browse",
			-command=>sub{$freq_other_142=FileDialog("Select other frequency file $chip")})->pack(-side => 'right');

 $f5->Label(-text => "\nGenetic map files for $chip",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'n');

 $f5->Label(-text => "\nDeCode",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e5=$f5->Entry(-width=>50, -textvariable=> \$decode_map_142)->pack(-side => 'right');
 my $b1_f5 = $f5->Button(-text => "Browse",
			-command=>sub{$decode_map_142=FileDialog("Select DeCode map file $chip ")})->pack(-side => 'right');

 $f6->Label(-text => "Marshfield",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e6=$f6->Entry(-width=>50, -textvariable=> \$marshf_map_142)->pack(-side => 'right');
 my $b1_f6 = $f6->Button(-text => "Browse",
			-command=>sub{$marshf_map_142=FileDialog("Select Marshfield map file $chip")})->pack(-side => 'right');

 $f7->Label(-text => "SLM1",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e7=$f7->Entry(-width=>50, -textvariable=> \$slm1_map_142)->pack(-side => 'right');
 my $b1_f7 = $f7->Button(-text => "Browse",
			-command=>sub{$slm1_map_142=FileDialog("Select SLM1 map file $chip")})->pack(-side => 'right');

 $f8->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e8=$f8->Entry(-width=>50, -textvariable=> \$other_map_142)->pack(-side => 'right');
 my $b1_f8 = $f8->Button(-text => "Browse",
			-command=>sub{$other_map_142=FileDialog("Select other map file $chip")})->pack(-side => 'right'); 
 }
 elsif ($chip eq "Xba240") {
 $f1->Label(-text => "Afro Americans",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e1=$f1->Entry(-width=>50, -textvariable=> \$freq_afam_240)->pack(-side => 'right');
 my $b1_f1 = $f1->Button(-text => "Browse",
			-command=>sub{$freq_afam_240=FileDialog("Select african american frequency file $chip")})->pack(-side => 'right');

 $f2->Label(-text => "Asians",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e2=$f2->Entry(-width=>50, -textvariable=> \$freq_asian_240)->pack(-side => 'right');
 my $b1_f2 = $f2->Button(-text => "Browse",
			-command=>sub{$freq_asian_240=FileDialog("Select asian frequency file $chip")})->pack(-side => 'right');

 $f3->Label(-text => "Caucasian",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e3=$f3->Entry(-width=>50, -textvariable=> \$freq_cauc_240)->pack(-side => 'right');
 my $b1_f3 = $f3->Button(-text => "Browse",
			-command=>sub{$freq_cauc_240=FileDialog("Select caucasian frequency file $chip")})->pack(-side => 'right');

 $f4->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e4=$f4->Entry(-width=>50, -textvariable=> \$freq_other_240)->pack(-side => 'right');
 my $b1_f4 = $f4->Button(-text => "Browse",
			-command=>sub{$freq_other_240=FileDialog("Select other frequency file $chip")})->pack(-side => 'right');

 $f5->Label(-text => "\nGenetic map files for $chip",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'n');

 $f5->Label(-text => "\nDeCode",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e5=$f5->Entry(-width=>50, -textvariable=> \$decode_map_240)->pack(-side => 'right');
 my $b1_f5 = $f5->Button(-text => "Browse",
			-command=>sub{$decode_map_240=FileDialog("Select DeCode map file $chip ")})->pack(-side => 'right');

 $f6->Label(-text => "Marshfield",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e6=$f6->Entry(-width=>50, -textvariable=> \$marshf_map_240)->pack(-side => 'right');
 my $b1_f6 = $f6->Button(-text => "Browse",
			-command=>sub{$marshf_map_240=FileDialog("Select Marshfield map file $chip")})->pack(-side => 'right');

 $f7->Label(-text => "SLM1",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e7=$f7->Entry(-width=>50, -textvariable=> \$slm1_map_240)->pack(-side => 'right');
 my $b1_f7 = $f7->Button(-text => "Browse",
			-command=>sub{$slm1_map_240=FileDialog("Select SLM1 map file $chip")})->pack(-side => 'right');

 $f8->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e8=$f8->Entry(-width=>50, -textvariable=> \$other_map_240)->pack(-side => 'right');
 my $b1_f8 = $f8->Button(-text => "Browse",
			-command=>sub{$other_map_240=FileDialog("Select other map file $chip")})->pack(-side => 'right'); 
 }

 elsif ($chip eq "Hind240") {
 $f1->Label(-text => "Afro Americans",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e1=$f1->Entry(-width=>50, -textvariable=> \$freq_afam_hind)->pack(-side => 'right');
 my $b1_f1 = $f1->Button(-text => "Browse",
			-command=>sub{$freq_afam_hind=FileDialog("Select african american frequency file $chip")})->pack(-side => 'right');

 $f2->Label(-text => "Asians",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e2=$f2->Entry(-width=>50, -textvariable=> \$freq_asian_hind)->pack(-side => 'right');
 my $b1_f2 = $f2->Button(-text => "Browse",
			-command=>sub{$freq_asian_hind=FileDialog("Select asian frequency file $chip")})->pack(-side => 'right');

 $f3->Label(-text => "Caucasian",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e3=$f3->Entry(-width=>50, -textvariable=> \$freq_cauc_hind)->pack(-side => 'right');
 my $b1_f3 = $f3->Button(-text => "Browse",
			-command=>sub{$freq_cauc_hind=FileDialog("Select caucasian frequency file $chip")})->pack(-side => 'right');

 $f4->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e4=$f4->Entry(-width=>50, -textvariable=> \$freq_other_hind)->pack(-side => 'right');
 my $b1_f4 = $f4->Button(-text => "Browse",
			-command=>sub{$freq_other_hind=FileDialog("Select other frequency file $chip")})->pack(-side => 'right');

 $f5->Label(-text => "\nGenetic map files for $chip",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'n');

 $f5->Label(-text => "\nDeCode",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e5=$f5->Entry(-width=>50, -textvariable=> \$decode_map_hind)->pack(-side => 'right');
 my $b1_f5 = $f5->Button(-text => "Browse",
			-command=>sub{$decode_map_hind=FileDialog("Select DeCode map file $chip ")})->pack(-side => 'right');

 $f6->Label(-text => "Marshfield",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e6=$f6->Entry(-width=>50, -textvariable=> \$marshf_map_hind)->pack(-side => 'right');
 my $b1_f6 = $f6->Button(-text => "Browse",
			-command=>sub{$marshf_map_hind=FileDialog("Select Marshfield map file $chip")})->pack(-side => 'right');

 $f7->Label(-text => "SLM1",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e7=$f7->Entry(-width=>50, -textvariable=> \$slm1_map_hind)->pack(-side => 'right');
 my $b1_f7 = $f7->Button(-text => "Browse",
			-command=>sub{$slm1_map_hind=FileDialog("Select SLM1 map file $chip")})->pack(-side => 'right');

 $f8->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e8=$f8->Entry(-width=>50, -textvariable=> \$other_map_hind)->pack(-side => 'right');
 my $b1_f8 = $f8->Button(-text => "Browse",
			-command=>sub{$other_map_hind=FileDialog("Select other map file $chip")})->pack(-side => 'right'); 
 }

 elsif ($chip eq "Nsp") {
 $f1->Label(-text => "Afro Americans",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e1=$f1->Entry(-width=>50, -textvariable=> \$freq_afam_nsp)->pack(-side => 'right');
 my $b1_f1 = $f1->Button(-text => "Browse",
			-command=>sub{$freq_afam_nsp=FileDialog("Select african american frequency file $chip")})->pack(-side => 'right');

 $f2->Label(-text => "Asians",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e2=$f2->Entry(-width=>50, -textvariable=> \$freq_asian_nsp)->pack(-side => 'right');
 my $b1_f2 = $f2->Button(-text => "Browse",
			-command=>sub{$freq_asian_nsp=FileDialog("Select asian frequency file $chip")})->pack(-side => 'right');

 $f3->Label(-text => "Caucasian",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e3=$f3->Entry(-width=>50, -textvariable=> \$freq_cauc_nsp)->pack(-side => 'right');
 my $b1_f3 = $f3->Button(-text => "Browse",
			-command=>sub{$freq_cauc_nsp=FileDialog("Select caucasian frequency file $chip")})->pack(-side => 'right');

 $f4->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e4=$f4->Entry(-width=>50, -textvariable=> \$freq_other_nsp)->pack(-side => 'right');
 my $b1_f4 = $f4->Button(-text => "Browse",
			-command=>sub{$freq_other_nsp=FileDialog("Select other frequency file $chip")})->pack(-side => 'right');

 $f5->Label(-text => "\nGenetic map files for $chip",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'n');

 $f5->Label(-text => "\nDeCode",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e5=$f5->Entry(-width=>50, -textvariable=> \$decode_map_nsp)->pack(-side => 'right');
 my $b1_f5 = $f5->Button(-text => "Browse",
			-command=>sub{$decode_map_nsp=FileDialog("Select DeCode map file $chip ")})->pack(-side => 'right');

 $f6->Label(-text => "Marshfield",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e6=$f6->Entry(-width=>50, -textvariable=> \$marshf_map_nsp)->pack(-side => 'right');
 my $b1_f6 = $f6->Button(-text => "Browse",
			-command=>sub{$marshf_map_nsp=FileDialog("Select Marshfield map file $chip")})->pack(-side => 'right');

 $f7->Label(-text => "SLM1",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e7=$f7->Entry(-width=>50, -textvariable=> \$slm1_map_nsp)->pack(-side => 'right');
 my $b1_f7 = $f7->Button(-text => "Browse",
			-command=>sub{$slm1_map_nsp=FileDialog("Select SLM1 map file $chip")})->pack(-side => 'right');

 $f8->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e8=$f8->Entry(-width=>50, -textvariable=> \$other_map_nsp)->pack(-side => 'right');
 my $b1_f8 = $f8->Button(-text => "Browse",
			-command=>sub{$other_map_nsp=FileDialog("Select other map file $chip")})->pack(-side => 'right'); 
 }
 
 elsif ($chip eq "Sty") {
 $f1->Label(-text => "Afro Americans",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e1=$f1->Entry(-width=>50, -textvariable=> \$freq_afam_sty)->pack(-side => 'right');
 my $b1_f1 = $f1->Button(-text => "Browse",
			-command=>sub{$freq_afam_sty=FileDialog("Select african american frequency file $chip")})->pack(-side => 'right');

 $f2->Label(-text => "Asians",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e2=$f2->Entry(-width=>50, -textvariable=> \$freq_asian_sty)->pack(-side => 'right');
 my $b1_f2 = $f2->Button(-text => "Browse",
			-command=>sub{$freq_asian_sty=FileDialog("Select asian frequency file $chip")})->pack(-side => 'right');

 $f3->Label(-text => "Caucasian",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e3=$f3->Entry(-width=>50, -textvariable=> \$freq_cauc_sty)->pack(-side => 'right');
 my $b1_f3 = $f3->Button(-text => "Browse",
			-command=>sub{$freq_cauc_sty=FileDialog("Select caucasian frequency file $chip")})->pack(-side => 'right');

 $f4->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e4=$f4->Entry(-width=>50, -textvariable=> \$freq_other_sty)->pack(-side => 'right');
 my $b1_f4 = $f4->Button(-text => "Browse",
			-command=>sub{$freq_other_sty=FileDialog("Select other frequency file $chip")})->pack(-side => 'right');

 $f5->Label(-text => "\nGenetic map files for $chip",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'n');

 $f5->Label(-text => "\nDeCode",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e5=$f5->Entry(-width=>50, -textvariable=> \$decode_map_sty)->pack(-side => 'right');
 my $b1_f5 = $f5->Button(-text => "Browse",
			-command=>sub{$decode_map_sty=FileDialog("Select DeCode map file $chip ")})->pack(-side => 'right');

 $f6->Label(-text => "Marshfield",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e6=$f6->Entry(-width=>50, -textvariable=> \$marshf_map_sty)->pack(-side => 'right');
 my $b1_f6 = $f6->Button(-text => "Browse",
			-command=>sub{$marshf_map_sty=FileDialog("Select Marshfield map file $chip")})->pack(-side => 'right');

 $f7->Label(-text => "SLM1",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e7=$f7->Entry(-width=>50, -textvariable=> \$slm1_map_sty)->pack(-side => 'right');
 my $b1_f7 = $f7->Button(-text => "Browse",
			-command=>sub{$slm1_map_sty=FileDialog("Select SLM1 map file $chip")})->pack(-side => 'right');

 $f8->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e8=$f8->Entry(-width=>50, -textvariable=> \$other_map_sty)->pack(-side => 'right');
 my $b1_f8 = $f8->Button(-text => "Browse",
			-command=>sub{$other_map_sty=FileDialog("Select other map file $chip")})->pack(-side => 'right'); 
 }
 
 else {
 $f1->Label(-text => "Afro Americans",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e1=$f1->Entry(-width=>50, -textvariable=> \$freq_afam_illumi)->pack(-side => 'right');
 my $b1_f1 = $f1->Button(-text => "Browse",
			-command=>sub{$freq_afam_illumi=FileDialog("Select african american frequency file $chip")})->pack(-side => 'right');

 $f2->Label(-text => "Asians",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e2=$f2->Entry(-width=>50, -textvariable=> \$freq_asian_illumi)->pack(-side => 'right');
 my $b1_f2 = $f2->Button(-text => "Browse",
			-command=>sub{$freq_asian_illumi=FileDialog("Select asian frequency file $chip")})->pack(-side => 'right');

 $f3->Label(-text => "Caucasian",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e3=$f3->Entry(-width=>50, -textvariable=> \$freq_cauc_illumi)->pack(-side => 'right');
 my $b1_f3 = $f3->Button(-text => "Browse",
			-command=>sub{$freq_cauc_illumi=FileDialog("Select caucasian frequency file $chip")})->pack(-side => 'right');

 $f4->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e4=$f4->Entry(-width=>50, -textvariable=> \$freq_other_illumi)->pack(-side => 'right');
 my $b1_f4 = $f4->Button(-text => "Browse",
			-command=>sub{$freq_other_illumi=FileDialog("Select other frequency file $chip")})->pack(-side => 'right');

 $f5->Label(-text => "\nGenetic map files for $chip",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'n');

 $f5->Label(-text => "\nDeCode",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e5=$f5->Entry(-width=>50, -textvariable=> \$decode_map_illumi)->pack(-side => 'right');
 my $b1_f5 = $f5->Button(-text => "Browse",
			-command=>sub{$decode_map_illumi=FileDialog("Select DeCode map file $chip ")})->pack(-side => 'right');

 $f6->Label(-text => "Marshfield",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e6=$f6->Entry(-width=>50, -textvariable=> \$marshf_map_illumi)->pack(-side => 'right');
 my $b1_f6 = $f6->Button(-text => "Browse",
			-command=>sub{$marshf_map_illumi=FileDialog("Select Marshfield map file $chip")})->pack(-side => 'right');

 $f7->Label(-text => "SLM1",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e7=$f7->Entry(-width=>50, -textvariable=> \$slm1_map_illumi)->pack(-side => 'right');
 my $b1_f7 = $f7->Button(-text => "Browse",
			-command=>sub{$slm1_map_illumi=FileDialog("Select SLM1 map file $chip")})->pack(-side => 'right');

 $f8->Label(-text => "Other",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e8=$f8->Entry(-width=>50, -textvariable=> \$other_map_illumi)->pack(-side => 'right');
 my $b1_f8 = $f8->Button(-text => "Browse",
			-command=>sub{$other_map_illumi=FileDialog("Select other map file $chip")})->pack(-side => 'right'); 
 } 
 my $b1=$f9->Button(-text=>"OK",
             -width=>10,-height=>1,-command=>sub{destroy $MW2;})->pack(-side => 'top',-anchor =>'n');
 $MW2->focusForce;

 MainLoop();
}


#############################  M A P   F U N K T I O N  ####################### 
sub MW4MapFunction {
 
	my $MW4=MainWindow->new();
	$MW4->title("Map Function");
	my $f0 = $MW4->Frame->pack(-side=>'top',-fill=>'x');
	my $f1 = $MW4->Frame->pack(-side=>'top',-fill=>'x');
	my $f2 = $MW4->Frame->pack(-side=>'top',-fill=>'x');

 	$f0->Label(-text=>"Select Map Function",-font=>'Arial 10 normal',-foreground=>'Blue',-width=>30,-height=>4)->pack;

	foreach (qw(Haldane Kosambi)) {
		my $rb1_f0=$f0->Radiobutton(-text 	=> $_,
			-value 	=> $_,
			-variable => \$mapfunc)-> pack(-side => 'top');
	}
	my $b1=$f0->Button(-text=>"OK",-width=>10,-height=>1,-command=>sub{destroy $MW4;})
				->pack(-side => 'top');
 MainLoop();
}

##################  O P T I O N  F I L E  S E L E C T I O N   ##################

sub MW6PhenoSelection {
 
 my $MW6=MainWindow->new();
 $MW6->title("Phenotype Options");

 my $f0 = $MW6->Frame->pack(-side=>'top',-fill=>'x');
 my $f1 = $MW6->Frame->pack(-side=>'top',-fill=>'x');
 my $f2 = $MW6->Frame->pack(-side=>'top',-fill=>'x');
 my $f3 = $MW6->Frame->pack(-side=>'top',-fill=>'x');
 my $f4 = $MW6->Frame->pack(-side=>'top',-fill=>'x');
 my $f5 = $MW6->Frame->pack(-side=>'top',-fill=>'x');
 my $f6 = $MW6->Frame->pack(-side=>'top',-fill=>'x');
 my $f9 = $MW6->Frame->pack(-side=>'top',-fill=>'x');

 $f0->Label(-text => "\nPhenotype Options",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'n');

 $f2->Label(-text => "If the trait is quantitative enter the name of the QTL-file\nFormat is tab-delimited: SAMPLEID TRAIT1 TRAIT2 TRAIT3,...,",
 	-font=>'Arial 10 normal')->pack(-side =>'top',-anchor => 'w');
 $f2->Label(-text => "else the qualitative trait from the pedfile.pro will be used\n",
 	-font=>'Arial 10 normal')->pack(-side =>'top',-anchor => 'w');

 $f3->Label(-text => "QTL file",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e3=$f3->Entry(-width=>40,-background=>'grey',-state =>'disabled', -textvariable=> \$qtlfile)->pack(-side => 'right');
 my $b1_f3 = $f3->Button(-text => "Browse",
			-command=>sub{$qtlfile=FileDialog("Select QTL file")})->pack(-side => 'right');

 $f1->Checkbutton(-text => "Trait is Quantitative",-command=>sub{if($qtl_select == 1){$e3->configure(-background=>'white',-state =>'normal');}
 else {$e3->configure(-background=>'grey',-state =>'disabled');}}, -font=>'Arial 10 normal',-foreground=>'red3',-variable => \$qtl_select)-> pack(-side => 'top',-anchor =>'nw');

 $f9->Button(-text=>"OK",
             -width=>10,-height=>1,-command=>sub{destroy $MW6;})->pack(-side => 'top',-anchor =>'n');
 $MW6->focusForce;
 MainLoop();
}

##############################  M W 7  G R R  F I L E  ########################## 

sub MW7GRRFile {
 
 my $MW7=MainWindow->new();
 $MW7->title("Options for GRR file");

 my $f0 = $MW7->Frame->pack(-side=>'top',-fill=>'x');
 my $f1 = $MW7->Frame->pack(-side=>'top',-fill=>'x');
 my $f2 = $MW7->Frame->pack(-side=>'top',-fill=>'x');
 my $f3 = $MW7->Frame->pack(-side=>'top',-fill=>'x');
 my $f4 = $MW7->Frame->pack(-side=>'top',-fill=>'x');
 my $f5 = $MW7->Frame->pack(-side=>'top',-fill=>'x');

 my $f9 = $MW7->Frame->pack(-side=>'top',-fill=>'x');

 $f0->Label(-text => "\nSelection of markers for GRR file",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'n');

 $f2->Label(-text => "GRR will not work with hundred thousands of markers,\nmay be 6000 informative markers are enough.\n",
 	-font=>'Arial 10 normal')->pack(-side =>'top',-anchor => 'n');
 $f2->Label(-text => "Example: Select markers every 200000 bases\n and with a minor allele freqency >0.20\n",
 	-font=>'Arial 10 normal')->pack(-side =>'top',-anchor => 'n');

 $f3->Label(-text => "number of bases distance",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 $f3->Entry(-width=>20, -textvariable=> \$minbases)->pack(-side => 'right');
 $f4->Label(-text => "minor allele frequency",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 $f4->Entry(-width=>20, -textvariable=> \$minfreq)->pack(-side => 'right');

 $f9->Button(-text=>"OK",
             -width=>10,-height=>1,-command=>sub{destroy $MW7;})->pack(-side => 'top',-anchor =>'n');
 $MW7->focusForce;
 MainLoop();
}

########################  M W 8  S N P  S E L E C T I O N  ##################### 

sub MW8SNPSelect {
 
 my $MW8=MainWindow->new();
 $MW8->title("Options for linkage analysis");

 my $f0 = $MW8->Frame->pack(-side=>'top',-fill=>'x');
 my $f1 = $MW8->Frame->pack(-side=>'top',-fill=>'x');
 my $f2 = $MW8->Frame->pack(-side=>'top',-fill=>'x');
 my $f3 = $MW8->Frame->pack(-side=>'top',-fill=>'x');
 my $f4 = $MW8->Frame->pack(-side=>'top',-fill=>'x');
 my $f5 = $MW8->Frame->pack(-side=>'top',-fill=>'x');
 my $f6 = $MW8->Frame->pack(-side=>'top',-fill=>'x');
 my $f7 = $MW8->Frame->pack(-side=>'top',-fill=>'x');
 my $f8 = $MW8->Frame->pack(-side=>'top',-fill=>'x');
 my $f9 = $MW8->Frame->pack(-side=>'top',-fill=>'x');

 $f0->Label(-text => "\nSelection of markers for linkage analysis",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'n');

 $f2->Label(-text => "Example: Select markers every 100000 bases\n and with a minor allele frequency >0.10\n",
 	-font=>'Arial 10 normal')->pack(-side =>'top',-anchor => 'n');

 $f3->Label(-text => "number of bases distance",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e1=$f3->Entry(-width=>20, -textvariable=> \$msminbases)->pack(-side => 'right');
 $f4->Label(-text => "minor allele frequency",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e2=$f4->Entry(-width=>20, -textvariable=> \$msminfreq)->pack(-side => 'right');

 $f1->Checkbutton(-text => "Select markers by distance and allele frequency",-command=>sub{if($select_dist == 1)
 			{$e1->configure(-background=>'white',-state =>'normal');$e2->configure(-background=>'white',-state =>'normal');}
 	else 	{$e1->configure(-background=>'grey',-state =>'disabled');$e2->configure(-background=>'grey',-state =>'disabled');}},
  -font=>'Arial 10 normal',-foreground=>'red3',-variable => \$select_dist)-> pack(-side => 'top',-anchor =>'nw');

 $f6->Label(-text => "chromosome",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e3=$f6->Entry(-width=>20, -textvariable=> \$mschrom)->pack(-side => 'right');
 $f7->Label(-text => "first position (bases)",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e4=$f7->Entry(-width=>20, -textvariable=> \$firstmspos)->pack(-side => 'right');
 $f8->Label(-text => "last position (bases)",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e5=$f8->Entry(-width=>20, -textvariable=> \$lastmspos)->pack(-side => 'right');

 $f5->Checkbutton(-text => "Select markers by chromosome, first and last position",-command=>sub{if($select_pos == 1)
 			{$e3->configure(-background=>'white',-state =>'normal');$e4->configure(-background=>'white',-state =>'normal');$e5->configure(-background=>'white',-state =>'normal');}
 	else 	{$e3->configure(-background=>'grey',-state =>'disabled');$e4->configure(-background=>'grey',-state =>'disabled');$e5->configure(-background=>'grey',-state =>'disabled');}},
  -font=>'Arial 10 normal',-foreground=>'red3',-variable => \$select_pos)-> pack(-side => 'top',-anchor =>'nw');

 $f9->Button(-text=>"OK", -width=>10,-height=>1,
 			-command=>sub{ MarkerSelection(); destroy $MW8;})->pack(-side => 'left',-anchor =>'n');
 $f9->Button(-text=>"Cancel", -width=>10,-height=>1,
			-command=>sub{destroy $MW8;})->pack(-side => 'right',-anchor =>'n');
 $MW8->focusForce;
 MainLoop();
}

###########################  M W 9  A L I A S  N A M E S  ###################### 
sub MW9Alias {
 
	my $MW9=MainWindow->new();
	$MW9->title("Alias name");
	my $f0 = $MW9->Frame->pack(-side=>'top',-fill=>'x');
	my $f1 = $MW9->Frame->pack(-side=>'top',-fill=>'x');
	my $f2 = $MW9->Frame->pack(-side=>'top',-fill=>'x');

 	$f0->Label(-text=>"Select SNP name",-font=>'Arial 10 normal',-foreground=>'Blue',-width=>30,-height=>4)->pack;

	foreach (qw(SNP_A-ID rs-number)) {
		my $rb1_f0=$f0->Radiobutton(-text 	=> $_,
			-value 	=> $_,
			-variable => \$aliasname)-> pack(-side => 'top');
	}
	my $b1=$f0->Button(-text=>"OK",-width=>10,-height=>1,-command=>sub{destroy $MW9;})
				->pack(-side => 'top');
 MainLoop();
}

#############################  M A P   F U N K T I O N  ####################### 
sub MW10MerlinTrait {
	if ($command_line == 0) {
		my $MW10=MainWindow->new();
		$MW10->title("Merlin - All in One option");
		my $f0 = $MW10->Frame->pack(-side=>'top',-fill=>'x');
		my $f1 = $MW10->Frame->pack(-side=>'top',-fill=>'x');
		my $f2 = $MW10->Frame->pack(-side=>'top',-fill=>'x');

	 	$f0->Label(-text=>"Select trait option",-font=>'Arial 11 normal',-foreground=>'Blue',-width=>30,-height=>4)->pack;

	 	$f1->Label(-text=>"Option \"noTrait\" will print output files\n without trait column\nthis is for simulation of genotypes only\n",-font=>'Arial 10 normal',-width=>40,-height=>4)->pack;

		foreach (qw(withTrait noTrait)) {
			my $rb1_f0=$f1->Radiobutton(-text 	=> $_,
				-value 	=> $_,
				-variable => \$merlin_all_trait)-> pack(-side => 'top');
		}
		my $b1=$f1->Button(-text=>"OK",-width=>10,-height=>1,-command=>sub{destroy $MW10; PrintSimuFiles();})
					->pack(-side => 'top');
		MainLoop();
	}
	else { PrintSimuFiles(); }
}

##########  Calculate allele frequencies, callrate, genotypes, HWE  ############ 
sub MW11CalcAllFreq {
 
	my $MW11=MainWindow->new();
	$MW11->title("Select individuals for calculation");
	my $f0 = $MW11->Frame->pack(-side=>'top',-fill=>'x');
	my $f1 = $MW11->Frame->pack(-side=>'top',-fill=>'x');
	my $f2 = $MW11->Frame->pack(-side=>'top',-fill=>'x');

 	$f0->Label(-text=>"Select genotyped individuals for calculation of\nallele frequencies, callrate, genotypes and HWE",
 			-font=>'Arial 10 normal',-foreground=>'Blue',-width=>40,-height=>4)->pack;

	foreach ("all individuals","founders only","unaffected founders","affected non-founders") {
		$f0->Radiobutton(-text 	=> $_,
			-value 	=> $_,
			-variable => \$sample_set)-> pack(-side => 'top',-anchor =>'w');
	}
	my $b1=$f2->Button(-text=>"OK",-width=>10,-height=>1,-command=>sub{destroy $MW11;CalcAllFreq();})
				->pack(-side => 'left');
	my $b2=$f2->Button(-text=>"Cancel", -width=>10,-height=>1,
			-command=>sub{destroy $MW11;})->pack(-side => 'right',-anchor =>'se');
	MainLoop();
}

##############################  M W 5  P E D S T A T  ########################## 
sub MW5PedStat {
	my $pedfile="pedfile.pro";
	my $MW5=MainWindow->new();
	$MW5->title("Select file for pedigree summary statistic");
	my $f0 = $MW5->Frame->pack(-side=>'top',-fill=>'x');
	my $f1 = $MW5->Frame->pack(-side=>'top',-fill=>'x');
	my $f2 = $MW5->Frame->pack(-side=>'top',-fill=>'x');
	my $f9 = $MW5->Frame->pack(-side=>'top',-fill=>'x');

	$f0->Label(-text=>"Select linkage format pedigree file",-font=>'Arial 10 normal',-foreground=>'Blue',-width=>30,-height=>4)->pack;

	$f1->Label(-text => "pedfile",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
	my $e1=$f1->Entry(-width=>30, -textvariable=> \$pedfile)->pack(-side => 'right');
	my $b1_f1 = $f1->Button(-text => "Browse",
			-command=>sub{$pedfile=FileDialog("Select linkage format pedfile")})->pack(-side => 'right');
	$f2->Label(-text => " ",-font=>'Arial 10 normal')->pack(-side =>'top');

	my $b1=$f9->Button(-text=>"OK", -width=>10,-height=>1,
			-command=>sub{destroy $MW5; PedStat($pedfile)}) ->pack(-side => 'left');
	my $b2=$f9->Button(-text=>"Cancel", -width=>10,-height=>1,
			-command=>sub{destroy $MW5;})->pack(-side => 'right',-anchor =>'se');
	MainLoop();
}

#################################  P E D S T A T  ############################## 
sub PedStat {
# pedstat.pl v1.4
# Pedigree file summary statistics
# Copyright (c)Franz Rueschendorf 2005
#
	my $infile = shift;
	ShowOutput ("\n#########################  PEDFILE SUMMARY STATISTICS ##########################\n\n");

	my $lfam="XXX";	# last familyname
	my $cfam=0;		# number of families
	my @fams=();	# array family names
	my %peds=();	# hash counts of family names 

	my $affdad=0;	# affected male founder
	my $affmom=0;	# affected female founder
	my $aff_found_nosex=0;	# affected no-sex founder
	my $affson=0;	# affected male non-founder
	my $affdau=0;	# affected female non-founder
	my $aff_nfound_nosex=0;	# affected no-sex non-founder

	my $mafound=0;	# male founder
	my $fefound=0;	# female founder
	my $nosex_found=0;	# no-sex founder
	my $cson=0;		# number of male non-founders
	my $cdau=0;		# number of female non-founders
	my $nosex_nfound=0;	# no-sex non-founders

	my $cindfam=0;	# number of individuals in current family
	my $affinfam=0;	# number of affecteds in current family
	my @iaff=();	# value-number of families with i-affecteds
	my @ifam=();	# value-number of families with i-members
	my $maxaff=0;	# maximal number of affecteds in one family
	my $maxind=0;	# maximal number of individuals in one family

	my $cind=0;		# total number of individuals in pedfile 
	my $affpers=0;	# number of affected individuals in pedfile
	my $unknown=0;	# number of unknown coded individuals in pedfile
	my $naff=0;		# number of not affected individuals in pedfile

	my $naff_found=0;	# not affected founder
	my $unk_found=0;	# unknown founder
	my $naff_nfound=0;	# not affected non-founder
	my $unk_nfound=0;	# unknown non-founder

	my $sex0=0;		# number of individuals coded sex-unknown

	my $skip=0;		# 0-linkage format, 1-skip one column

	############################  R E A D  I N F I L E  ############################

	my ($first,$fam,$ind,$dad,$mom,$sex,$aff,@rest);
	
	
	open (IN, "$infile") || print "could not open infile $infile :$!\n";

	while (<IN>){
		next if /^$/;
		next if /^#/;
		next if /^\*/;
		chomp();
		if ($skip==0) {		# linkage format
			($fam,$ind,$mom,$dad,$sex,$aff,@rest)=split(' ',$_);
		}
		else { 				# first column is DNA-number, then linkage format
			($first,$fam,$ind,$dad,$mom,$sex,$aff,@rest)=split(' ',$_);
		}

		if (($fam eq "") || ($ind eq "")) { next; }	# empty fields, but tabs
		
		##---------- new family ---------##
		if ($fam ne $lfam ) {
			push (@fams,$fam); 
			$cfam++;
			if ($lfam ne "XXX"){
				$iaff[$affinfam]++;
				if ($affinfam > $maxaff) { $maxaff = $affinfam; }
				$ifam[$cindfam]++;
				if ($cindfam > $maxind) { $maxind = $cindfam; }
			}
			$cindfam=0;
			$affinfam=0;
			$lfam=$fam;
		}
		##-------------------------------##
		
		$cind++;
		$cindfam++;

		if ($aff == 2) {
			if (( $dad eq "0") && ($sex == 1)) { $affdad++; }
			if (( $dad eq "0") && ($sex == 2)) { $affmom++; }
			if (( $dad eq "0") && ($sex == 0)) { $aff_found_nosex++; }	### no-sex
			if (( $dad ne "0") && ($sex == 1)) { $affson++; }
			if (( $dad ne "0") && ($sex == 2)) { $affdau++ }
			if (( $dad ne "0") && ($sex == 0)) { $aff_nfound_nosex++ }	# no-sex
			$affinfam++;
			$affpers++; 
		}

		if ($aff == 1) { $naff++; }
		if ($aff == 0) { $unknown++; }
		if (( $dad eq "0") && ($sex == 1)) { $mafound++; }
		if (( $dad eq "0") && ($sex == 0)) { $nosex_found++; }	### no-sex
		if (( $dad eq "0") && ($sex == 2)) { $fefound++; }
		if (( $dad eq "0") && ($aff == 1)) { $naff_found++; }
		if (( $dad eq "0") && ($aff == 0)) { $unk_found++; }
		
		if (( $dad ne "0") && ($sex == 1)) { $cson++; }
		if (( $dad ne "0") && ($sex == 2)) { $cdau++; }
		if (( $dad ne "0") && ($sex == 0)) { $nosex_nfound++; }	### no-sex
		if (( $dad ne "0") && ($aff == 1)) { $naff_nfound++; }
		if (( $dad ne "0") && ($aff == 0)) { $unk_nfound++; }
		
		if ($sex == 0) { ${sex0}++; }
	}
	close (IN);

	$iaff[$affinfam]++;	# 
	if ($affinfam > $maxaff) { $maxaff = $affinfam; }
	$ifam[$cindfam]++;
	if ($cindfam > $maxind) { $maxind = $cindfam; }
	
	foreach (@fams){ $peds{$_}++; }


	############################  W R I T E  O U T F I L E  ########################   

	ShowOutput("Infile: $infile\t\t$datum\n\n");

	my $aff_found=$affdad + $affmom + $aff_found_nosex;
	my $aff_nfound = $affson + $affdau + $aff_nfound_nosex;
	my $pers_total=$affpers + $naff + $unknown;
	my $found_total= $aff_found + $naff_found + $unk_found;
	my $nfound_total = $aff_nfound + $naff_nfound + $unk_nfound;

	ShowOutput(sprintf("total number of families         : %4s \n",$cfam));
	ShowOutput("-----------------------------------------\n\n");

	for (my $i=1;$i<=$maxind;$i++) {
		if ( $ifam[$i] > 0) {
			ShowOutput(sprintf("families with %2d members         : %4d \n",$i,$ifam[$i]));
		}
	}
	ShowOutput("\n");

	for (my $i=0;$i<=$maxaff;$i++) {
		if ( $iaff[$i] > 0) {		
			ShowOutput(sprintf("families with %2d affecteds       : %4d \n",$i,$iaff[$i]));
		}
	}
	
	ShowOutput("\n\n");
	ShowOutput(sprintf("total number of individuals   : %4s\n",$cind));
	ShowOutput("------------------------------------------\n\n");

	ShowOutput("                founder   non-founder total     \n");
	ShowOutput("                ---------------------------\n");
	ShowOutput(sprintf("affected         %4s       %4s       %4s\n", $aff_found,$aff_nfound,$affpers));
	ShowOutput(sprintf("not affected     %4s       %4s       %4s\n",$naff_found,$naff_nfound,$naff));
	ShowOutput(sprintf("unknown          %4s       %4s       %4s\n",$unk_found,$unk_nfound,$unknown));
	ShowOutput("                ---------------------------\n");
	ShowOutput(sprintf("total            %4s       %4s       %4s\n\n\n",$found_total,$nfound_total,$pers_total));

	ShowOutput(sprintf("affected male   founder          : %4s \n",$affdad));
	ShowOutput(sprintf("affected female founder          : %4s \n",$affmom));
	if (($aff_found_nosex > 0) || ($aff_nfound_nosex > 0)) { ShowOutput(sprintf("affected sex-unknown founder     : %4s \n",$aff_found_nosex)); }
	ShowOutput(sprintf("affected male   non-founder      : %4s \n",$affson));
	ShowOutput(sprintf("affected female non-founder      : %4s \n",$affdau));
	if (($aff_found_nosex > 0) || ($aff_nfound_nosex > 0)) { ShowOutput(sprintf("affected sex-unknown non-founder : %4s \n",$aff_nfound_nosex)); }
	ShowOutput("\n");

	ShowOutput(sprintf("total male   founder             : %4s \n",$mafound));
	ShowOutput(sprintf("total female founder             : %4s \n",$fefound));
	if (($nosex_found > 0 ) || ($nosex_nfound > 0 )) { ShowOutput(sprintf("total sex-unknown founder        : %4s \n",$nosex_found)); }
	ShowOutput(sprintf("total male   non-founder         : %4s \n",$cson));
	ShowOutput(sprintf("total female non-founder         : %4s \n",$cdau));
	if (($nosex_found > 0 ) || ($nosex_nfound > 0 )) { ShowOutput(sprintf("total sex-unknown non-founder    : %4s \n",$nosex_nfound)); }
	ShowOutput("\n");
	
	foreach (sort keys %peds){
		if ($peds{$_} > 1) { ShowOutput("ERROR: may be family $_ is splittet in pedfile\n");}
	}

	if ($sex0 > 0) {
		if ( $sex0 == 1) { ShowOutput("\nWARNING: there is $sex0 individual coded sex-unknown\n"); }
		else { ShowOutput("\nWARNING: there are $sex0 individuals coded sex-unknown\n"); }
		ShowOutput("WARNING: some linkage programs will show mysterious error messages\n");
	}
	ShowOutput ("#################################################################################\n\n");
}


###############################  S H O W  H E L P  ############################ 
sub ShowHelp {

	my $help = $mw->Toplevel(-title => "Alohomora $version Help");	
	my $scr_x  = $mw->screenwidth;
	my $scr_y  = $mw->screenheight;
	my $mw_szx = 0.7;
	my $mw_szy = 0.6;
	my $helptxt="";

	$help->geometry (
		int($scr_x*$mw_szx) . 'x' . int($scr_y * $mw_szy) .  '+' .
		int($scr_x*(1-$mw_szx)/2) . '+' . int($scr_y * (1-$mw_szy)/3)
	);
	
	my $t = $help->Scrolled('Text',
		-scrollbars => 'osoe',
		-font => 'Courier 9 normal',
		-bg => 	'#f4e3aa'
	)->pack(-fill => 'both', -expand => 1);
	
   while (<DATA>) { $helptxt .= $_; }
   	
	$t->insert('end',$helptxt);
	
# 	$help->idletasks;	
}

###########################  Eval Command Line    ##############################

sub GetArguments {
	GetOptions(
		"p=s" => \$pedfilepro,
		"g=s" => \$infile,
		"b=s" => \$batch_file,
		"nogui" => \$command_line,
		"help|?|h" => \$clhelp
	);
}
#############################   D R U C K E N    ###############################

sub Drucken {
	system "emacs @_";	# use WordPad or your favorite editor
}

##################################  H E L P  ###################################

sub CommandLineHelp {
	print "\nALOHOMORA $version\n";
	print "(c) 2003-2017 Franz Rueschendorf\n";
	print "usage: alohomora [<options>]\n\n";
	print "options:\n";
	print "\t--nogui             command line modus\n";
	print "\t--help|-?|-h        this help\n";
	print "\t-p <pedfile.pro>    file containing the pedigree structure and affection status\n";
	print "\t-g <genotypefile>   file containing the genotype calls\n";
	print "\t-b <batchfile>      alohomora batch file\n";
	
	print "\n";
	exit;
}
############################   S P E I C H E R N   #############################

sub Savefile {
	
	$outfile="${base_no_ext}\.log";
	if (-f $outfile) { move ($outfile,"${outfile}0");}
	open (FH, "> $outfile");
	foreach (@alog) {
		print FH "$_";
	}
	close (FH);
	print "Window saved in $outfile!\n";
	Errormsg("Window saved in file\n$outfile\n");
}

###########################   F I L E  D I A L O G    ##########################

sub FileDialog
{
 my $name = $mw->getOpenFile(-title=>"@_");
 return ($name);
}

###########################   W R I T E   L O G    #############################

sub WriteLog {
	$outfile="$targetdir/alohomora_create\.log";
	open (FH, "> $outfile");
	foreach (@alog) {
		print FH "$_";
	}
	#	print FH $tb->get("1.0","end");
	close (FH);
}
#############################   B E E N D E N    ###############################

sub Quit {
	$outfile="alohomora\.log";
	if (-f $outfile) { move ($outfile,"${outfile}0");}
	open (FH, "> $outfile");
	foreach (@alog) {
		print FH "$_";
	}
#	print FH $tb->get("1.0","end");
	close (FH);	
	if ($command_line == 0) {$mw->destroy;}
	exit 0;
}
#################################   E N D E   ##################################


__DATA__

====================
ALOHOMORA v0.32 HELP
====================



====================
INTRODUCTION
====================


  ALOHOMORA is a software tool designed to facilitate genome-wide linkage
  studies performed with high-density single nucleotide polymorphism (SNP)
  marker panels such as the Affymetrix GeneChip(R) Human Mapping 10K Array.

  ALOHOMORA combines information about pedigree structure, affection status,
  marker allele frequencies, genetic and physical map with genotype data.
  It manages quality control of genotype data and data conversion into different
  formats for linkage and association analysis. Three genetic maps (deCODE,
  Marshfield and SLM1) as well as allele frequencies from three ethnic populations
  (African American, Asian and Caucasian) can optionally be selected by the user
  (data from the Affymetrix SNP annotation files). 
  Additional Perl-scripts are used to start analysis programs like Allegro,
  Aspex, Fbat, Genehunter, Merlin, Plink, without graphical user-interface on
  different platforms.  Likewise results can be plotted with the help of 
  Perl-scripts and Gnuplot. 



================================================================================
FORMAT
================================================================================

PEDIGREE FILE:
-------------

  The pedigree file has the standard linkage format. 
  Columns are whitespace-delimited. 
  Alohomora reads the first 6 columns, additional columns are allowed.
  The signs # and * comment out a line.
  Default name is "pedfile.pro".

  FAMILY_ID SAMPLE_ID FATHER_ID MOTHER_ID SEX AFFECTION_STATUS

  Example:

   1    401       0       0    1    1
   1   2737       0       0    2    1
   1   2738     401    2737    2    1
   1   2212     401    2737    2    2
   1   2213     401    2737    1    2



GENOTYPE FILE:
-------------

  The genotype file has one header line describing the columns.
  The first column contains the SNP name and ALL other columns contain 
  genotype data. Columns are TAB-delimited.
  The genotypes must be coded AA or A for homozygote on the first allele,
  BB or B for homozygote on the second allele and AB for heterozygote.

  To get the sample IDs from the columns header Alohomora removes at first an
  ending "_Call", then the string is splittet by a field separator like "_",
  if there results one or two fields, then the first field is used as
  sample ID, else the third field is used.

  SNP_NAME	SAMPLE1	SAMPLE2	SAMPLE3	SAMPLE4	...

  Example:

   SNP ID       	CBE_EX1_2212_140503_Xba131_Call  CBE_EX1_2213_140503_Xba131_Call
   SNP_A-1509443	AA	AB	...
   SNP_A-1518557	BB	AB	...
   SNP_A-1517286	AB	AB	...
   ...
   or

   SNP ID       	2212	2213	...
   SNP_A-1509443	AA	AB	...
   SNP_A-1518557	BB	AB	...
   SNP_A-1517286	AB	AB	...
   ...



GENETIC MAP FILE:
----------------

  The first line in the genetic map file is a header line 
  describing the TAB-delimited columns.
  The first 6 columns are:

   1. Chromosome
   2. SNP name
   3. Genetic position
   4. Physical position
   5. Rs-number
   6. Cytoband

  Additional columns are allowed. 
  The signs # and * at first character in a line will comment out this line.
  This file must be sorted by 1) chromosome and 2) genetic position.



ALLELE FREQUENCY FILE:
---------------------

  The first line in the allele frequency file is a header line 
  and will be skipped by Alohomora. 
  The first two columns are:

   1. SNP name
   2. Frequency of A allele

  Additional columns are allowed; the columns are whitespace-delimited.
  Missing values for the allele frequency are indicated by "---".
  For missing values Alohomora will insert equal distributed allele 
  frequencies (0.5,0.5) when creating the linkage datain file.
  

================================================================================
GETTING STARTED
================================================================================

  usage: alohomora [<options>]
  options:
     --nogui             batch modus
     --help|-?|-h        this help
     -p <pedfile.pro>    file containing the pedigree structure and affection status
     -g <genotypefile>   file containing the genotype calls
     -b <batchfile>      alohomora batch file
  When started ALOHOMORA reads at first variables from alohomora.ini (if available),
  then, if --nogui is specified ALOHOMORA tries to read commands from alohomora.bch. 



Combining SNP names:
--------------------

  The SNP name in the a) genotype file (column 1), b) genetic map file (column 2)
  and c) allele frequency file (column 1) must be the same,
  either a TSC-number, a Affymetrix SNP ID or the rs-number. 
  In the Affymetrix SNP annotation files not all SNPs have an rs-number or 
  TSC-number. Therefore I provide files with the Affymetrix SNP ID as identifier
  (http://gmc.mdc-berlin.de/alohomora/maps).

  There is the possibility to use the rs-number (if available in the map file) 
  for the linkage format data files with the Alohomora option: 
    Menu -> Options -> Alias names
  But the quality control, e.g. PedCheck, Merlin error detection, has to be done
  with the original marker identifier. 



How to create an allele frequency file from my data set:
--------------------------------------------------------
  
  a) load data: Button "Read Infiles"
  b) select Menu -> Utilities -> Calculate allele frequencies,Callrate,HWE
  c) select between "all individuals", "founders only", ...
  d) press OK



Substitution of resource files:
-------------------------------

  There is an easy way to specify alternative file names. 
  With the Alohomora option
    Menu  -> Options -> File selection
  the user selects e.g. a different genetic map file or an allele frequency file
  estimated from the data set.


================================================================================
CITATION
================================================================================

If you use ALOHOMORA in any published work please cite:

Ruschendorf F, Nurnberg P.
ALOHOMORA: a tool for linkage analysis using 10K SNP array data.
Bioinformatics. 2005 May 1;21(9):2123-5.


===============================================================================

FRANZ RSCHENDORF, 31-Jul-2009

===============================================================================