#! /opt/gensoft/adm/bin/perl
use lib "/opt/gensoft/exe/alohomora/v0.36/lib/perl5";
#
# ALOHOMORA_M.PL
#
# Slow version of ALOHOMORA for Mega SNP Arrays
# 
# Quality Control and Data Conversion of SNP Array Genotypes for Gene Mapping Projects
# Copyright (c) Franz Rschendorf 2003-2010
#
# 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
# 29-Aug-2005, 100K/500K implementations, Chips Xba240 and Nsp
# 30-Aug-2005, GRR marker selection
# 08-Sep-2005, PedCheck, PlotPedCheckErr bugs
# 09-Sep-2005, Illumina, BrowseEntry
# 13-Sep-2005, PedCheck, load 10000, calculate 1000
# 14-Sep-2005, load genotypes from multiple files
# 18-Sep-2005, MakeNoLimitFiles dynamic load genotypes
# 18-May-2006, Genotype-format: AA,A,0 ; BB,B,2 ; AB,1 ; NC,-1		# for BRLMM output
# 25-Sep-2006, Haploview with physical map
# 02-Oct-2006, Command line modus
# 23-Oct-2006, output to PLINK
# 18-Nov-2006, Show Help
# 31-Dec-2006, Calculate Callrate
# 24-Jan-2007, additional Show Help
# 02-Apr-2007, Select markers for linkage analysis
# 09-Feb-2008, Illumina300
# 31-Mar-2009, change in order: when apply skiplist and marker selection together
# 23-Jun-2009, Alias name
# 10-Aug-2009, filter functions revised
# 11-Aug-2009, GW6 chip inserted
# 17-Sep-2009, bug in GW6 chip selection corrected
# 21-Oct-2009, Function "Utilities -> Calling rate" (by sample) revised
# 28-Nov-2012, Function "Utilities -> Calling rate" (by sample) revised
# 10-Jul-2013, CheckGender NoCall : gtyp =~ /N/
# 04-Dec-2013, Select markers for GRR, new calculation of maxfreq

use Tk;
use Cwd;
# use strict;
use File::Copy;
use File::Basename;
use Getopt::Long;
use Tk::BrowseEntry;	### DOS , comment out in UNIX
use Tk::FileSelect;	### DOS , comment out in UNIX

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

my $mapdir="/opt/gensoft/exe/alohomora/v0.36/share";
# my $map_dir="C:/genetics/affy";			### DOS workPC
# 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;
my $statusgtyphdr=0;
my $statusped=0;
my $statusmap=0;
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=();		# merged skiplist
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 unlikely genotypes identified by Merlin 
my $del_unl_th=0.05;	# delete unlikely genotypes with RATIO < threshold 

#----- Read Genotypes -----#
my $infile="";			# GDAS output genotype file
my $basename="";		# Base Filename
my $base_no_ext="";	# Basename no extension
my $dirname=();
my @head=();			# Array Headerline
my $snp="";				# SNPname
my %samples=();		# hash, key is sample ID
my %choice=();			# Selection marker
my $readGtyp=0;
my $loadsize=200000;	# number of markers to load in hash
my $maxmkr=0;			# last position of marker loaded from @snplist
my $FS="-";				# samplename field separator

#---- Hash Genotypes  ----#
my %gtype=();	# hash containing all genotypes $gtype{$pid}{$marker}
my @names=();	# replaced with Hash
my %gnames=();	# Hash: names of all SNPs used from genotype file (minus skipped data)


#------ 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=();			# members of this family @{$menbers{$fam}}

#------ 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 used for PedCheck

#------ 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_gw6="$map_dir/GW6_map_decode_na23_2007-07-18.txt";	# GW6
my $marshf_map_gw6="$map_dir/GW6_map_marshf_na23_2007-07-18.txt";
my $slm1_map_gw6="$map_dir/GW6_map_slm1_na23_2007-07-18.txt";
my $other_map_gw6="";

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

#tim
my $decode_map_illumi300k="";	# Illumina 
my $marshf_map_illumi300k="";
my $slm1_map_illumi300k="";
my $other_map_illumi300k="$map_dir/Illumina300k_map_Other.txt";	# Illumina 

my $noposfile="";
my @koord=();					# all the genetic map data
my @xlist=();
my @ylist=();
my @mtlist=();
my @xarray=();
my @yarray=();
my @mtarray=();
my @autolist=();
my @nokoordlist=();
my @koordlist=();	# all markers (with position) in order of @koord
my %nopos=();
my %autohash=();
my @autoarray=();
my $genmap="DeCode";			# default map
my $mapfunc="Haldane";		# default map function
my %alias=();
my $aliasname="SNP_A-ID";		# alias rs-number

#------ 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="$map_dir/Xba142_freqA_adipositas.txt";	# 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="$map_dir/Nsp_freqA_asian.txt";	# 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_gw6="$map_dir/GW6_freqA_Yoruban_na23.txt";		# AfroAmericans
my $freq_asian_gw6="$map_dir/GW6_freqA_Han_Chinese_na23.txt";	# Asians
my $freq_cauc_gw6="$map_dir/GW6_freqA_Caucasian_na23.txt";		# Caucasians
my $freq_other_gw6="$map_dir/GW6_freqA_Japanese_na23.txt";	# 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

#tim
my $freq_afam_illumi300k="";		# AfroAmericans
my $freq_asian_illumi300k="";	# Asians
my $freq_cauc_illumi300k="$map_dir/Illumina300k_freqA_cauc.txt";		# Caucasians
my $freq_other_illumi300k="";	

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

#------------  GRR  ------------#
my $grrfile="grr_pedfile.dat";	# Infile for Graphical Relationship Representation
my $minbases=200000;
my $minfreq=0.35;
my $maxfreq=1-$minfreq;

#------ 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=();
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- no moving window
my $fp=0.9999;				# disease locus wildtype frequency
my $fq=0.0001;				# disease locus mutant frequency
my $pvf1="0.000";			# penetrances
my $pvf2="0.000";
my $pvf3="1.000";
my $pvf4="1.000";			# for Imprinting model only

##------  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";
my $not_inf_file="non_informative.txt";


#--- Calc Allele frequencies ---#
my $frqfile="alleles.frq";
my $sample_set="founders only";
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;

print "ALOHOMORA_M $version\n";

my $operating_system = $^O;
my $terminal='windows';
print "\nOperating system: $operating_system\n";
if ($operating_system =~ /solaris|linux/) {
    $terminal='x11';
}

if (-f "$saveenv"){ &LoadEnv;}
&GetArguments;
if ($clhelp == 1) { &CommandLineHelp; exit(0); }

if ($command_line == 1) { &RunBatch;}
else {

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

$mw = MainWindow->new(-title=>"Alohomora_M $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{ReadGenotypeFile()}],
						[ Button => "Print",-command => sub {Drucken($outfile);} ],
						[ Button => "Save",-command => \&Savefile  ] ])
						->pack	(-side		=>"left" );
$file_menu->separator();
$file_menu->command(-label		=> "Quit", -command 	=> sub {exit});

$file_menu = $menubar->Menubutton(	-text => "Check", -menuitems => [
						[ Button => "Compare sampleIDs",-command => sub {CompareSampleIDs()}],
						[ Button => "Gender",-command => sub {CheckGender()}],
						[ Button => "Make 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 {PrintSimuFiles()}],
						[ Button => "Plink",-command => sub {Plink()}],
						])
						->pack	(-side		=>"left" );

$file_menu = $menubar->Menubutton(	-text => "Options", -menuitems => [
						[ Button => "Alias names",-command => sub {MW12Alias()}],
						[ Button => "File selection",-command => sub {FileSelection()}],
						[ Button => "Sample ID",-command => sub {MW9FS()}],
						[ Button => "Select markers for GRR",-command => sub {MW7GRRFile()}],
						[ Button => "Select markers for linkage analysis",-command => sub {MW10SNPSelect()}],
						[ Button => "Loadsize for genotype data",-command => sub {MW8LoadDataMode()}],
						[ 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');
#tim
my $be2f2=$f2->BrowseEntry( -width=>10, -listwidth=>25, -variable => \$chip);
foreach (qw(Xba131 Xba142 Xba240 Hind240 Nsp Sty GW6 Illumina Illumina300k)) { $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 =>"Chromosome\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   ##################################
################################################################################

##############################  R U N  B A T C H  ##############################
sub RunBatch {
	
	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";
		print "Infile: $infile\n";
		print "Pedfile: $pedfilepro\n";
	}
	else {
		print "No file $batch_file, run default batch\n\n";
		&ReadInfiles;
		&CompareSampleIDs;
		&CheckGender;
		&PrintGRRFile;
		$del_errors=0;
		&PedCheck;
		&PlotPedCheckErr;
		$del_errors=1;	
		&Merlin;
		system("merlin_start.pl");	### UNIX
#		system("merlin_start");	### DOS batch
		&CreMerlinErrList;
#		$del_unlikely=1;		
#		&Plink;
#		&Allegro;
	}
}

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

sub ReadInfiles {
	ShowOutput("ALOHOMORA_M $version\n");
	ShowOutput("Date: $datum\nPath: $work_dir\n");
	if ($infile eq "") {$infile=FileDialog("select GDAS genotype file");}
	$dirname=dirname($infile);
	if (($work_dir ne $dirname) and ($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;
	&ReadNotInf;
	&ReadGtypHeader;
	&ReadPedfilePro;
	&ReadQTLfile;
	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 ("\nNot found skiplist : $skipfile\n");
		}	
	}
	else {
		print "\nSkiplist not selected\n";
		ShowOutput ("\nSkiplist not selected\n");
	}
}


###################  N O T  I N F O R M A T I V E  L I S T  ####################

sub ReadNotInf {
	@allhomozygote=();
	%allhomoz=();
	if ($skip_notinf == 1) { # Skip SNPs which are not informative 
		$nr=0;
		if (-f $not_inf_file) {
			print "Read marker list     : $not_inf_file\n";
			ShowOutput ("\nRead marker list : $not_inf_file");
			open (IN, "$not_inf_file") || die "could not open $not_inf_file :$!\n";
			while (<IN>){
				next if /^$/;
				next if /^#/;
				chomp;
				my @v=split(' ',$_);
				push (@allhomozygote,$v[0]); $nr++;	# create array SNPs to skip
				$allhomoz{$v[0]}=1;
			}
			close (IN);
			ShowOutput("\t$nr SNPs not informative\n");
			$statusstat == 1;
		}
		else {
			print "Not found markerlist : $not_inf_file\n";
			ShowOutput ("\nNot found markerlist : $not_inf_file\n");
		}	
	}
}

#######################  R E A D  G T Y P  H E A D E R  ########################

sub ReadGtypHeader {
	ShowOutput ("\nRead genotypefile(s) header line\n");	
	%samples=();	# hash all samples: $samples{$sampleID} = count 
	my @files=glob("$infile");	# alle Genotypenfiles im Affy Format
	print "ReadGtypHeader:\n";
  	for (my $i=0;$i<=$#files;$i++) {		# fr jeden Infile
		my $c_snp= -1;
		my $file=$files[$i];
#		my $schalt=0;
		open (IN, "$file") || die "could not open genotypefile $file :$!\n";
		print "\t$file\n";	
		ShowOutput ("\t$file\n");	
		while (<IN>){
			next if /^$/;
			next if /^Dynam/;
			chomp;
			if (($_ =~ /SNP ID/)||($_ =~ /SNP_ID/)||($_ =~ /probeset id/)) {		# modify GMC Daten
				my @h=split('\t',$_);
				for (my $z=0;$z<=$#h;$z++) {	# parse header line
					if (($h[$z] eq "SNP ID")||($h[$z] eq "SNP_ID") ||($h[$z] eq "probeset id")) {$c_snp=$z;}			
					elsif ($h[$z] =~ /_Call/) {	#
						$h[$z] =~ s/_Call//;
						
						my $pid="";
						my @f=split($FS,$h[$z]);	# split experiment name with field separator 							
						if ($#f > 1) {
							$pid=$f[2];
							($pid=$f[2]) =~ s/^00//;		# fr GMC Daten
							$pid =~ s/^0//;
#							$pid =~ s/^GE//;
							$samples{$pid}++;}  # sampleID in 3th field
						else {
							$pid=$f[0];
							($pid=$f[0]) =~ s/^00//;		# fr GMC Daten
							$pid =~ s/^0//;
#							$pid =~ s/^GE//;
							$samples{$pid}++;}	# Hash SampleID in Spalte $z #					
					}				
 					else {print "\t$h[$z] not used\n";}
				}
				last;
			}
#			if ($schalt == 1)  {last;}
		}
		close (IN);
		if ($c_snp < 0) { ShowOutput ("no SNP ID line in $file\n");}
	}	
	my $nr= (keys %samples);
	ShowOutput ("\t$nr samples\n");
	print "\t$nr samples\n";
	$statusgtyphdr=1;
}


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

sub ReadGenotypeFile {

	%gtype=();		# all genotypes loaded in hash : $gtype{$pid}{$snp}
	%gnames=();		# all markers loaded (all in genotypefile - skipped markers)
	keys (%gnames)=($loadsize+1);
	@skip=();	# initialize skiplist
	my %skiplist=();	# Hash (key is SNP-name)
	%samples=();	# hash all samples: $samples{$sampleID} = count 

	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) {
		if ($status_PedCheckErr == 0) { &ReadPedCheckErr;}
		push(@skip,@errorlist);	# Skip SNPs with errors
	}
	foreach (@skip) {	# Creates hash from skiplist
		$skiplist{$_}=1;
	}

### Test
#	my $var=(keys %choice);
#	print "Number of entries in Choice: $var\n";
#	my $var=(keys %gtype);
#	print "Number of entries in gtype: $var\n";
		
	
	my @files=glob("$infile");	# alle Genotypenfiles im Affy Format
	for (my $i=0;$i<=$#files;$i++) {		# fr jeden Infile
		my $file=$files[$i];

		my %sample=();		# alle samples im aktuellen genotypen file: sample{spalte}=sampleID
		my $c1=0;	# all SNP-lines in infile
		my $c2=0;	# SNPs not skipped
		my @sam=();	# Spalten-nummer in der ein "_Call" steckt
		my $c_sam=0;
		my $c_snp=0;	# Spalte mit SNP ID
		my $pid="";
		my $schalt=999999;
		
		print "Read genotypefile\t: $file";
		ShowOutput("Read genotypefile : $file\n");
		open (IN, "$file") || die "could not open genotypefile $file :$!\n";
LINE1:	while (<IN>){
			next LINE1 if /^$/;
			next LINE1 if /^#/;
			next LINE1 if /^Dynam/;
#			next LINE1 if /^AFFX/;
			chomp;
			if ($schalt == 999999 and ($_ =~ /SNP ID/)||($_ =~ /SNP_ID/)||($_ =~ /probeset id/)) {
				@head=split('\t',$_);
				for (my $z=0;$z<=$#head;$z++) {	# parse header line
					if (($head[$z] eq "SNP ID") ||($head[$z] eq "SNP_ID")||($head[$z] eq "probeset id")){$c_snp=$z;}			
					elsif ($head[$z] =~ /_Call/) {	#
						$head[$z] =~ s/_Call//;

						my @feld=split($FS,$head[$z]);	  ### GMC Trennzeichen
						if ($#feld > 1) {
							$pid=$feld[2];
							$pid =~ s/^00//;
							$pid =~ s/^0//;
#							$pid =~ s/^GE//;
							$sample{$z}=$pid;$samples{$pid}++;
						}  ############### SampleID in 3th field
						else {
							$pid=$feld[0];
							$pid =~ s/^00//;
							$pid =~ s/^0//;
#							$pid =~ s/^GE//;
							$sample{$z}=$pid; $samples{$pid}++;
						}	# Hash SampleID in Spalte $z #
						if (exists $indiv{$pid}) {	# wenn sample im pedfile.pro
							push (@sam, $z);
						}				
					}				
	 				else {print "\t$head[$z] not used\n";}
				}
				$schalt= $.;
				
			}
			if ($. > $schalt) {
				s/NoCall/NC/g;
				my @v=split('\t',$_);
				if ($v[0] eq "") {next LINE1;}
				$c1++;
				if (! exists $choice{$v[$c_snp]}) {next LINE1;}
				if ($skiplist{$v[$c_snp]}) {next LINE1;}	# don't read in this SNPs
				foreach (@sam) {				# Create hash genotypes
					$gtype{$sample{$_}}{$v[$c_snp]} = $v[$_];
				}
				$gnames{$v[$c_snp]}=1;
				$c2++;
			}
		}
		close (IN);
		
		my $c_samples=$#sam +1;
		print "\t$c_samples samples\n";
	
		my $c3=$c1-$c2;
		ShowOutput("\t$c_samples samples; $c2 of $c1 SNPs read in, $c3 skipped\n");
	}
	$statusdata=1;

	my $t_samples=0;
	foreach (keys %samples) { 
		$t_samples++; 
#		if ($samples{$_} > 1) {print "Doubled sample $_ $samples{$_}\n"; }
	}
	print "Total $t_samples samples\n";
	ShowOutput("Total $t_samples samples\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");
	my @data=();
	@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;
	}
}


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

sub ReadPedfilePro {  ## noch zu berarbeiten
	if ( ! -f $pedfilepro ){
		if ($command_line == 0) { 
			Errormsg("Pedfile.pro not found: $pedfilepro !");
		}
		else { 
			ShowOutput("\nPedfile.pro not found: $pedfilepro !");
			print "\nPedfile.pro not found: $pedfilepro!\n\n";
			exit 1;
			&Quit;
		}
#		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 "\nRead 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
		$count++;
		my ($fam,$ind,$dad,$mom,$sex,$aff,@rest) = @p;
#		$ind =~ s/^00//;	# remove leading 0's 
#		$ind =~ s/^0//;

		if ($aff == 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 - unaffected 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
		push (@{$member{$fam}},$ind);
	}
	close (fhin);
	my $nr=@affind;
	print "\taffected: $nr individuals\n";
#	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");
#	foreach (keys %indiv){ ShowOutput("$_ $indiv{$_}\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 ){
		if ($command_line == 0) {Errormsg("QTLfile not found $qtlfile !\n");}
		else {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 {
  	ShowOutput("\nStart PedCheck ");

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

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

	print "PrintPedcheckFile Pedfile: $pedcheckfile  Names: $namesfile  \n";
	print "Load genotype data in sets of $loadsize marker\n";
	print "Start PedCheck with $maxmarker per run\n\n";
	system "echo $datum > $pedcheckall";

	$linked = 'autosomal';

	@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;
	my $lastsnp=0;
	my $max=0;
	
	for (my $anz=0;$anz<=$#snplist;$anz+=$maxmarker) {# Pedcheck mit jeweils maxmarker SNPs aufrufen
		my $var=$anz+$maxmarker;
		my $anz1=$anz+1;
		print "Subset: $anz1 - $var\n";
		
		if ($anz >= $lastsnp) {
			my $i;
			$max = $anz + $loadsize;
			if ($max > $#snplist) { $max = $#snplist +1;}
			%choice = ();
			keys (%choice)=($loadsize);
			for ($i=$anz;$i<$max;$i++) {
				$choice{$snplist[$i]}=1;		# selection for ReadGenotypeFile
			}
			$lastsnp=$i;
			
			%gtype=();
			my $nr= (keys %samples);
			keys (%gtype)=($nr * $loadsize);			
	  		ShowOutput("\nLoad data $anz1 - $max\n");
			ReadGenotypeFile();
			if ($del_errors == 1) {&DelErrors;}
			if ($linked eq 'X-linked') {&DelHetMaleX;}
		}

		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")||($gtype{$ind[$i]}{$snplist[$k]} eq "0")) {print fhout " 1 1";}
					elsif (($gtype{$ind[$i]}{$snplist[$k]} eq "BB")||($gtype{$ind[$i]}{$snplist[$k]} eq "B")||($gtype{$ind[$i]}{$snplist[$k]} eq "2")){print fhout " 2 2";}
					elsif (($gtype{$ind[$i]}{$snplist[$k]} eq "AB")||($gtype{$ind[$i]}{$snplist[$k]} eq "1")) {print fhout " 1 2";}
					elsif (($gtype{$ind[$i]}{$snplist[$k]} eq "NC")||($gtype{$ind[$i]}{$snplist[$k]} eq "-1")) {print fhout " 0 0";}
					else {print fhout " X X";}
				}
			}
			print fhout "\n";
		}
		close (fhout);
		close (fh_names);
		ShowOutput(" .");

		&StartPedcheck;
		&CountGtypdpers;
		system "echo Marker number: $anz1 \- $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="/home/franz/bin/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="/home/franz/bin/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"
}

##########################  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
#    $c_snp=0;
    $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[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/) {
#			print "$_\n";
			$fam=$row[4]; # print "fam $fam";
			$snp=$row[8]; # print "snp $snp\n";
			$err{$fam}{$snp}++;
#			$c_snp{$row[8]}++;
#			$c_err++;
		}
	}
	close (IN);
	foreach (keys %c_snp) {
		push (@errorlist,$_);
	}
	$c_snp_err=$#errorlist + 1;

	print "Error list : $c_snp_err SNPs\n\n";
	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=();
	@ylist=();
	@mtlist=();
	@autolist=();
	@nokoordlist=();
	@koordlist=();	# all markers with position
	@xarray=();
	@yarray=();
	@mtarray=();
	@autoarray=();
	%autohash=();
	%nopos=();
#	@nokoordarray=();
	my $markermap="";
	%alias=();

	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 "GW6") {
		if ($genmap eq "DeCode") {$markermap=$decode_map_gw6;}
		elsif ($genmap eq "Marshf") {$markermap=$marshf_map_gw6;}
		elsif ($genmap eq "SLM1") {$markermap=$slm1_map_gw6;}
		else {$markermap=$other_map_gw6;}
	}
	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;}
	}
	elsif ($chip eq "Illumina300k") {                                           #tim
		if ($genmap eq "DeCode") {$markermap=$decode_map_illumi300k;}
		elsif ($genmap eq "Marshf") {$markermap=$marshf_map_illumi300k;}
		elsif ($genmap eq "SLM1") {$markermap=$slm1_map_illumi300k;}
		else {$markermap=$other_map_illumi300k;}
	}
	else {;}
		
	if ( ! -f $markermap) {
		print "Could not open markermap $markermap\n";
		ShowOutput("Could not open markermap $markermap\n");
		if ( $command_line ==1) { exit 1;}
		return;
	}
	
	ShowOutput("\nRead markermap      :\t$markermap\n");
	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
		chomp;
		$c_map++;
		push (@koord,$_);	# all
		my @v=split('\t',$_);
		if (($v[0] !~ /---/) && ($v[0] ne "")) { push (@koordlist,$v[1]);}
		if (($v[0] eq '23') || ($v[0] eq 'X')) {push (@xlist,$v[1]);push (@xarray,$_);}	# x-linked
		elsif (($v[0] eq '24') || ($v[0] eq 'XY')) {push (@autolist,$v[1]);}					# autosomal
		elsif (($v[0] eq '25') || ($v[0] eq 'Y')) {push (@ylist,$v[1]);push (@yarray,$_);}	# y-linked
		elsif (($v[0] eq '26') || ($v[0] eq 'MT') || ($v[0] eq 'mt')) {push (@mtlist,$v[1]);push (@mtarray,$_);}	# MT-linked
		elsif ($v[0] eq '---') {push (@nokoordlist,$v[1]); $nopos{$v[1]}=1;}		# no-position
		elsif ($v[0] > 0.) {push (@autolist,$v[1]);}					# autosomal
		else {push (@nokoordlist,$v[1]); $nopos{$v[1]}=1;}		# no-position

		if ($v[4] =~ /^rs/) {$alias{$v[1]}=$v[4];}
		else {$alias{$v[1]}=$v[1];}
	}

	close (IN);
	
	$statusmap=1;
	ShowOutput("\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=$#ylist+1;
	if ($var > 0) {
		print "\tY-linked      :\t$var marker\n";
		ShowOutput("\tY-linked    :\t$var marker\n");
	}
	$var=$#mtlist+1;
	if ($var > 0) {
		print "\tMT-linked      :\t$var marker\n";
		ShowOutput("\tMT-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");
	$var=@koordlist;
	ShowOutput("\twith position:\t$var markers\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 $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 "GW6") {
		if ($allfreq eq "AfAm") {$freqfile=$freq_afam_gw6;}
		elsif ($allfreq eq "Asian") {$freqfile=$freq_asian_gw6;}
		elsif ($allfreq eq "Caucasian") {$freqfile=$freq_cauc_gw6;}
		elsif ($allfreq eq "Other") {$freqfile=$freq_other_gw6;}
		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 = "";}
	}
	elsif ($chip eq "Illumina300k") {                                           #tim
		if ($allfreq eq "AfAm") {$freqfile=$freq_afam_illumi300k;}
		elsif ($allfreq eq "Asian") {$freqfile=$freq_asian_illumi300k;}
		elsif ($allfreq eq "Caucasian") {$freqfile=$freq_cauc_illumi300k;}
		elsif ($allfreq eq "Other") {$freqfile=$freq_other_illumi300k;}
		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");
		if ( $command_line ==1) { exit 1;}
		return;
	}
	ShowOutput("Read allele frequencies: $freqfile\n");
	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 =~ /---/) {next;} 	# skip no frequency available
		$fA=sprintf("%5.4f",$fA);
		if ($fA == 0) {$fA=0.00100;}
		if ($fA == 1) {$fA=0.99900;}
#		$fB=sprintf("%5.4f",1-$fA);
		$freqA{$snp}=$fA;
#		$freqB{$snp}=$fB;
	}
	close(IN);
	print "Read allele frequencies: $freqfile\n";
	$statusfreq=1;
	
}

##############################  P R I N T   G R R F I L E   ###########################
sub PrintGRRFile {
	if ($statusped == 0){&ReadPedfilePro;}
	if ($statusmap == 0){&ReadGenMap;}

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

	ShowOutput( "\nSelect markers for Graphical Relationship Representation\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 eq "23") || ($chrom eq "X")) {last;}
		if ($chrom ne $lastchrom) {
			$lastchrom = $chrom;
			$nextpos = 0.;
		}
		if (($physpos > $nextpos) && (exists $freqA{$marker})) {
			if  (($freqA{$marker} > $minfreq) && ($freqA{$marker} < $maxfreq)) {
				push (@grrlist,$marker);
#				ShowOutput( "$marker\t$chr\t$physpos\t$freqA{$marker}\n");
				
				$nextpos = $physpos + $minbases;
			}
		}
	}

	my $var = $#grrlist +1;	
	%choice = ();
	keys (%choice)=($var);
	foreach (@grrlist) { $choice{$_}=1;}	# selection for ReadGenotypeFile
	
	ReadGenotypeFile();
	
	open (fhout,"> $grrfile") || die "could not open GRR file $grrfile :$!\n";
	ShowOutput( "\nCreate file for Graphical Relationship Representation\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 Markerkarte

			if (! exists $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")||($gtype{$ind[$i]}{$marker} eq "0"))  {print fhout " 1/1";}
				elsif (($gtype{$ind[$i]}{$marker} eq "BB")||($gtype{$ind[$i]}{$marker} eq "B")||($gtype{$ind[$i]}{$marker} eq "2"))  {print fhout " 2/2";}
				elsif (($gtype{$ind[$i]}{$marker} eq "AB")||($gtype{$ind[$i]}{$marker} eq "1")) {print fhout " 1/2";}
				elsif (($gtype{$ind[$i]}{$marker} eq "NC")||($gtype{$ind[$i]}{$marker} eq "NoCall")||($gtype{$ind[$i]}{$marker} eq "-1")) {print fhout " 0/0";}
				else {print fhout " X/X";}
			}
#			$c++;
		}
#		print "$pedcheck[$i]\t\tgenotypes: $c\n";
		print fhout "\n";
	}
	close (fhout);
	ShowOutput( "\t$var autosomal markers selected\n");
	ShowOutput( "\tminimal distance between markers: $minbases\n\tminimal minor allele frequency: $minfreq\n");
	ShowOutput( "GRR file saved in $grrfile\n");
	print "GRR file saved in $grrfile\nDone \n";
}


##############   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;

	$targetdir="merlin_all";
	if (! -d $targetdir) { mkdir ($targetdir,0777); ShowOutput("Create directory $targetdir\n");}
	else {
		move ("merlin_all", "merlin.all0");
		Errormsg("Moved merlin.all to merlin.all0\n");return;
	}
	

	print "Create Merlin Files\n";
	my $var=$#autolist+1;
	print "Autosomal list has $var entries\n";

###	  neu 2011-07-20 ###
	%choice=();
	foreach (@autolist) { $choice{$_}=1;}	# selection for ReadGenotypeFile
	
	ReadGenotypeFile();
####  neu 2011-07-20 ###


	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";

	foreach (@autoarray) {			# for each autosomal SNP in map
		my @row=split('\t',$_);
		my ($chrom,$marker,$genpos,$phypos,@rest) = @row;
		$z++;
		# Skip SNPs in skiplist (nopos, non-informative, skip ME, list)
		if ($skiplist{$marker}) {next;}
		
		if (! exists $gnames{$marker}){next;}	# Skip if marker not in GDAS genotype file
		$genotyp{dummy}.=" 0 0";
		while (my ($key,$value)= each (%samples)) {
			if (! exists $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")||($gtype{$value}{$marker} eq "0"))  {$genotyp{$value}.=" 1/1";}
				elsif (($gtype{$value}{$marker} eq "BB")||($gtype{$value}{$marker} eq "B")||($gtype{$value}{$marker} eq "2"))  {$genotyp{$value}.=" 2/2";}
				elsif (($gtype{$value}{$marker} eq "AB")||($gtype{$value}{$marker} eq "1")) {$genotyp{$value}.=" 1/2";}
				elsif (($gtype{$value}{$marker} eq "NC")||($gtype{$value}{$marker} eq "-1")) {$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}) {
			my $fB=1-$freqA{$marker};
			print fhfrq "F $freqA{$marker} $fB\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++) {
# 		print fhout "$pedcheck[$i] ";
		print fhout "$pedfile[$i] ";
		if (! exists $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 {
	print "Check gender\n";
	ShowOutput("\nCheck gender of individuals\n");
	if ($statusmap==0) {&ReadGenMap;}

#	my $var = $#xlist +1;	
#	%choice = ();
#	keys (%choice)=($var);
#	foreach (@xlist) { $choice{$_}=1;}	# selection for ReadGenotypeFile
	
#	ReadGenotypeFile();	
	my $lfndnr=0;
	$maxmkr=0;
	my @markermap=@xarray;
	@snplist=@xlist;	

	my $var=0;
	my $sex="";
	my $del=0;
	my %het_male=();	# key is sampleID males, counts heterozygote genotypes
	my %het_snp=();		# key is marker , counts heterozygote males
	my %hetero=();		# counter heterozygote genotypes for each sample
	my %allgtps=();		# key is sample ID, counts all genotype calls
	open (OUT, "> male_het_on_X.out") || print "could not open valuefile male_het_on_X.out :$!\n";
	foreach $marker (@xlist) {			# fr jeden SNP in der Markerkarte

		$lfndnr += 1;
		if (($lfndnr > $maxmkr) && ($lfndnr <= $#snplist)) {
			&LoadData($lfndnr);
			print "\n";
		}
		foreach $var (keys %samples) {
			if (exists ($gtype{$var}{$marker})) {
				if (($gtype{$var}{$marker} !~ /N/) && ($gtype{$var}{$marker} ne "-1"))  {$allgtps{$var}++;}
				if (($gtype{$var}{$marker} eq "AB") || ($gtype{$var}{$marker} eq "1")){
					$hetero{$var}++;
					if ($gender{$var} == 1){
						$het_snp{$marker}++;
						$het_male{$var}++;
#						delete ($gtype{$var}{$marker}); # delete heterozygote X-linked genotypes on males
						print OUT "$marker\t$var\n";
						$del++;
					}
				}
			}
		}
	}
	close (OUT);
	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 (! exists $hetero{$key}) {$var=0.0}
		else {$var=$hetero{$key}/$allgtps{$key}*100;}
		$var=sprintf("%4.1f",$var);
		if ($var > 10) {$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");}
	}

	my ($ch, $marker, $genet, $phys, $rs, @rest);
	
	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 {;}
	%allgtps=();
	%het_male=();
	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;
			}

			$lastchrom=$v[0];
			push (@xsums,$xsum);###

		}
		$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;	  
	$lastxsum=$xsum;
	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 ="$c_snperr mendelian errors in Fam:${fams} ";
		$snperrfile="PedCheck_Fam${fams}\.out";
		$postfile="PedCheck_Fam${fams}\.ps";
	}
	else {
		$titel ="$c_snperr mendelian errors in ${fc} families ";
		$snperrfile="PedCheck_${fc}_fams\.out";
		$postfile="PedCheck_${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";
#	}

	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" ;
	print OUT "set xlabel \"cM\"\n";
	print OUT "set ylabel \"Counts\"\n";
	my $ypos = $ymax + (($ymax-$ymin)/14);
	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, \'$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 (! exists $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.5');
		}
		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]};}
		}
	}

	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}: chr $pchrom  mendelian errors in fam:${fams} ";
		$snperrfile="${base_no_ext}_fam${fams}_chr$pchrom\.out";
		$postfile="${base_no_ext}_fam${fams}_chr$pchrom\.ps";
	}
	else {
		$titel ="${basename}: chr $pchrom   mendelian errors in ${fc} families ";
		$snperrfile="${base_no_ext}_${fc}_fams_chr$pchrom\.out";
		$postfile="${base_no_ext}_${fc}_fams_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";
	if ( $command_line == 0) {
		print OUT "set terminal windows\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 (! exists $hashpos{$key}) {
			printf ("%2s %s\t%-13s %2s\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;}
		my $fB=1-$freqA{$marker};
		$var="$chrom\t$marker\t$genpos\t$phypos\t$freqA{$marker}\t$fB\n";	###
		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 ($statusgtyphdr == 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 (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 (keys %samples){if (! $indiv{$_}) {push(@v,$_);}}
	if ($#v < 0) {ShowOutput(" none\n");}
	else {ShowOutput("\n@v\n");}

	my $i=0;		# number of samples shared by genotype file and pedfile.pro
	ShowOutput("\nNumber of samples shared by genotype file and pedfile.pro:");
	foreach (keys %samples){if (exists $indiv{$_}) {$i++;}}
	ShowOutput(" $i\n");

	@v=();		# search for doubled sampleIDs in genotype file
	foreach (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 (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";
	MW2LinkageFiles();
}

sub Fbat {
	$selection="fbat";
	MW2LinkageFiles();
}

sub Genehunter {
	$selection="gh";
	MW2LinkageFiles();
}

sub Haploview {
	$selection="haploview";
	MW2LinkageFiles();
}

sub Merlin {
	$selection="merlin";
	MW2LinkageFiles();
}

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

sub Plink {
	$selection="plink";
	MW2LinkageFiles();
}


##############################  L O A D  D A T A  ##############################          
sub LoadData {
	my $begin=shift;

	$begin -= 1;
	$maxmkr = $begin + $loadsize;

#	print "begin\t$begin\nloadsize\t$loadsize\nmaxmkr\t$maxmkr\n";
#	print "erster marker: $snplist[$begin]\n";

	if ($maxmkr > $#snplist) { $maxmkr = $#snplist + 1}
	%choice = ();
	keys (%choice)=($loadsize);
	for ( my $i=$begin;$i<$maxmkr;$i++) {
		$choice{$snplist[$i]}=1;		# selection for ReadGenotypeFile
	}
#	my $ofile="choice_$begin.txt";
#	open (OUT,"> $ofile") || die "could not open $ofile :$!\n";
#	foreach my $key (keys %choice) {
#		print OUT "$key\n";
#	}
#	close (OUT);
	
	%gtype=();
	my $nr= (keys %samples);
	keys (%gtype)=($nr * $loadsize);
	$begin += 1;
	ShowOutput("\nLoad data $begin - $maxmkr\n");
	ReadGenotypeFile();
	
	if ($del_errors == 1) {&DelErrors;}
	if ($del_unlikely == 1) {&DelUnlikely;}
}

####################  M A K E   L I N K A G E   F I L E S     ##################
sub MakeNoLimitFiles {
	$all_markers=0;
	my $aref;
	my @maptmp=();
	print "Sub MakeNoLimitFiles\n";
	my $lastgenpos="0";
	$lastchrom="00";
	my $lfndnr=0;
	$maxmkr=0;

	if ($status_markerlist == 1) {
		$aref=\@markerlist;
		@snplist=();
		foreach (@$aref) {
			my @row=split('\t',$_);
			my ($chrom,$marker,$genpos,$phypos,@rest) = @row;
			push (@snplist,$marker);
		}
		my $nr=@snplist;
		ShowOutput("\nSNPlist hat $nr markers\n");
	}
	else {
		@snplist=();
		&InitializeSkiplist;
		foreach (@koord) {	# select SNPs from genetic map 
			my ($chrom,$marker,$genpos,$physpos,@rest)=split('\t',$_);
			if (	exists $skiplist{$marker}) {next;}
			push (@maptmp,$_);
			push (@snplist,$marker);
		}
		$aref=\@maptmp;
	}


LINE4: foreach (@$aref) {			# for each SNP in genetic map

		my @row=split('\t',$_);
		my ($chrom,$marker,$genpos,$phypos,@rest) = @row;

		$lfndnr += 1;
		if (($lfndnr > $maxmkr) && ($lfndnr <= $#snplist)) {
			&LoadData($lfndnr);
			if (($lastchrom eq "23") || ($lastchrom eq "X")) {&DelHetMaleX;}
			print "\n";
		}
		
      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 ($chrom eq '23') {&DelHetMaleX;}

			if (! -d "$targetdir/$chr_dir" ) {mkdir ("$targetdir/$chr_dir", 0777);}
			$lastchrom=$chrom;
			$lastgenpos=-0.1;
			$nr=0;
			@mapout=();
			%genotyp=();
		}
		
		if (exists $gnames{$marker}){	# Is this marker in genotypefile list?
			$nr++;
			if (($genpos <= $lastgenpos) && ($chrom eq $lastchrom)) {
				$genpos=$lastgenpos+0.0002;
			}
			$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");
			}
	
###		
#			push (@mapout,"$chrom\t$genpos\t$marker\t$phypos\t$nr");
			$genotyp{dummy}.=" 0 0";
			foreach my $pid (keys %samples) {

				if (! exists $gtype{$pid}{$marker}) { # Not in Hash if not genotyped
					$genotyp{$pid}.=" 0 0";
				}
				else {	# if genotyped then recode the Hash value and print
					if	  (($gtype{$pid}{$marker} eq "AA")||($gtype{$pid}{$marker} eq "A")||($gtype{$pid}{$marker} eq "0"))  {$genotyp{$pid}.=" 1 1";}
					elsif (($gtype{$pid}{$marker} eq "BB")||($gtype{$pid}{$marker} eq "B")||($gtype{$pid}{$marker} eq "2"))  {$genotyp{$pid}.=" 2 2";}
					elsif (($gtype{$pid}{$marker} eq "AB")||($gtype{$pid}{$marker} eq "1")) {$genotyp{$pid}.=" 1 2";}
					elsif (($gtype{$pid}{$marker} eq "NC")||($gtype{$pid}{$marker} eq "-1")) {$genotyp{$pid}.=" 0 0";}
					else {$genotyp{$pid}.=" 0 0";
						print "unknown genotype: $gtype{$pid}{$marker} : $pid : $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 $hapview_mapfile="$targetdir/$chr_dir/haploview_map\.$lastchrom";
	my $merl_mapfile="$targetdir/$chr_dir/merlin_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";
	#tim
	my $merlin_paramfile="$targetdir/$chr_dir/param.tbl";
	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 (! exists $genotyp{$ind[$i]}) {print OUT "$genotyp{dummy}";}
			else { print OUT "$genotyp{$ind[$i]}";}

			###### QTL traits ######
			if (! exists $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 (! exists $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 %4s\n",$z[0],$z[1],$z[2],$z[3],$z[4]);
	}
	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);

		#tim
		if ($targetdir eq "merlin") {
			open (OUTTIM, ">$merlin_paramfile");
			print OUTTIM "TRAIT\t$fq\t$pvf1,$pvf2,$pvf3\tPARAM_MODEL";
			close OUTTIM;
		}
		#tim

	}

#---------------------------  mapfile Haploview  ----------------------------###
	if ($targetdir eq "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 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',$_);
			$z[0] =~ s/^0//;
			if ($z[0] eq "24") { $z[0] = 25;}
			printf OUT ("%s %13s %12.8f %10d\n",$z[0],$z[2],$z[1],$z[3]);
		}
		close (OUT);
		### haploview map
		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);
		
	}

#-------------------------------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 eq "23") || ($lastchrom eq "X")) { 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 eq "23") || ($lastchrom eq "X")) { print OUT " 0.001 0.990\n";}
	}
	else {
		print OUT " $pvf1 $pvf2 $pvf3 $pvf4\n";
		if (($lastchrom eq "23") || ($lastchrom eq "X")) { 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]}) {
			my $fB=sprintf("%8.4f",1-$freqA{$z[2]});			
			print OUT " $freqA{$z[2]} $fB\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("%11.8f",($z[1] - $lastpos));
			if ($diff == 0) { $diff=0.0001;} # 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 Funktion
				$theta=sprintf("%7.6f",((1-exp(-(2 * $diff/100))) / 2)); 
			}
			if ($theta == 0) {$theta= 0.000001;}
			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;	# index des arrays @koord
	my $cw=0;		# counts repeated markers in next set
	my $aref;
	$all_markers=0;
	@ghunix=();			# gh_start_sh unix
	@swunix=();			# sw_lod_start_sh unix
	@ghdos=();			# gh_start_bat DOS
	my $lastgenpos="0";
	$lastchrom="00";

	my $lfndnr=0;  ##250
	$maxmkr=0;		##250

	my @markermap=();
	if ($status_markerlist == 1) {
		$aref=\@markerlist;
		@snplist=();
		foreach (@$aref) {
			my @row=split('\t',$_);
			my ($chrom,$marker,$genpos,$phypos,@rest) = @row;
			push (@snplist,$marker);
		}
		my $nr=@snplist;
		ShowOutput("\nSNPlist has $nr markers\n");
	}
	else {
		$aref=\@koord;
		@snplist=@koordlist;
		&InitializeSkiplist;

	}



LINE3: for ($w=0;$w<=$#$aref;$w++) {			# fr jeden SNP in der Markerkarte
		my @row=split('\t',$aref->[$w]);
		my ($chrom,$marker,$genpos,$phypos,@rest) = @row;
		$lfndnr += 1;
		if (($lfndnr > $maxmkr) && ($lfndnr <= $#snplist)) {
			&LoadData($lfndnr);
			print "\n";
			if (($lastchrom eq "23") || ($lastchrom eq "X")) {&DelHetMaleX;}		
		}

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

		# Skip SNPs in sjkiplist
		if ($skiplist{$marker}) {next LINE3;}

		if (($genpos < $lastgenpos)&& ($chrom eq $lastchrom) && ($nr > 0)) {
			$genpos=$lastgenpos+0.0001;
			print "Position of marker $marker is smaller than last position. Sort mapfile!\n";
			ShowOutput("Position of marker $marker is smaller than last position. Sort mapfile!\n");
		}

		if (($genpos == $lastgenpos)&& ($chrom eq $lastchrom) && ($nr > 0)) {
			$genpos=$lastgenpos+0.0001;
			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");
		}


		$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;
			if ($chrom eq '23') {&DelHetMaleX;}		
			$nr=0;
			@mapout=();
			%genotyp=();
			$vnr=0;
		}

		if ($gnames{$marker}) {
			$nr++;
			push (@mapout,"$chrom\t$genpos\t$marker\t$phypos\t$nr");
			$genotyp{dummy}.=" 0 0";
			foreach my $value (keys %samples) {

				if (! exists $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")||($gtype{$value}{$marker} eq "0"))  {$genotyp{$value}.=" 1 1";}
					elsif (($gtype{$value}{$marker} eq "BB")||($gtype{$value}{$marker} eq "B")||($gtype{$value}{$marker} eq "2"))  {$genotyp{$value}.=" 2 2";}
					elsif (($gtype{$value}{$marker} eq "AB")||($gtype{$value}{$marker} eq "1")) {$genotyp{$value}.=" 1 2";}
					elsif (($gtype{$value}{$marker} eq "NC")||($gtype{$value}{$marker} eq "-1")) {$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";
	#tim
	my $merlin_paramfile="$targetdir/$chr_dir/param.tbl";

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

#-------------------------------Genehunter BATCH------------------------###
  if ($selection eq "gh") {
	if (($lastchrom eq "23") || ($lastchrom eq "X")) { 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 (! exists $genotyp{$ind[$i]}) {print OUT "$genotyp{dummy}";}
			else { print OUT "$genotyp{$ind[$i]}";}

			###### QTL traits ######
			if (! exists $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 (! exists $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);
		#tim
		open (OUTTIM, ">$merlin_paramfile");
		print OUTTIM "TRAIT\t$fq\t$pvf1,$pvf2,$pvf3\tPARAM_MODEL";
		close OUTTIM;
		#tim
	}

#------------------------------- 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 eq "23") || ($lastchrom eq "X")) { 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 eq "23") || ($lastchrom eq "X")) { print OUT " 0.001 0.990\n";}
	}
	else {
		print OUT " $pvf1 $pvf2 $pvf3 $pvf4\n";
		if (($lastchrom eq "23") || ($lastchrom eq "X")) { 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]}) {
			my $fB=1-$freqA{$z[2]};			
			print OUT " $freqA{$z[2]} $fB\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 ($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 "theta eq 0, inserted 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 ($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";}
	if ($mapfunc eq "Kosambi") {print OUT "map kosambi\n";} # map func
	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) {
				$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="";

	if ($status_PedCheckErr == 0) { &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");
	
}

############  D E L E T E   heterozygote G E N O T Y P E S  from males on X  #############
#
# Check gender has to be carried out before
# this creates a file 
#
sub DelHetMaleX {
	my $infile="male_het_on_X.out";
	if (! -f "$infile") { ShowOutput("$infile not found: no deletion of male het X genotypes\n");}
	else {

		my $c_del=0;
		open (IN,"$infile") || die "could not open $infile :$!\n";
		while (<IN>){
			next if /^$/;
			chomp;
			my @v=split(' ',$_);
			if (exists $gtype{$v[1]}{$v[0]}) {
				delete ($gtype{$v[1]}{$v[0]});
				$c_del++;
			}
		}
		close (IN);
		
		print "$c_del entries in hash genotypes deleted\n";
		ShowOutput("$c_del genotypes from heterozygote males deleted\n");
	}
}

######################   F I L E  S T A T I S T I K    #########################
sub CallingRate {	# counts genotypes and do some statistics
	if ($statusgtyphdr == 0) {
		Errormsg("No data loaded!\nPlease enter genotypefile and read files!\n");
		return;
	}
	print "Calculate calling rate\n";
	ShowOutput("Calculate calling rate\n");

	my %allsamples=();	# all sample names in all genotype files
	my %allmarkers=();	# all marker names in all genotype files
	my %skipped=();		# all marker names not used in this calculation

	my %nocall=();		# number of NoCalls for each sample: $nocall{$pid} counts
	my %nc=();			# number of NoCalls for each SNP: $nc{$snp} counts
	my %AA=();			# number of AA and NC calls for a SNP
	my %BB=();			# number of BB and NC calls for a SNP
	my $c_nocalls=0;	# number of NoCalls all together
	my %SampleCalls=();	# number of calls per sample $SampleCalls{pid} = call_counts
	
	%allhomoz=();
	@allhomozygote=();	# List of markers which are not informative
	$skip_notinf = 0;
	&InitializeSkiplist;

	my $sams= (keys %samples);	# number of samples in genotype files

################################################################################ neu ###
	my @files=glob("$infile");	# alle Genotypenfiles im Affy Format
	for (my $i=0;$i<=$#files;$i++) {		# fr jeden Infile
		my $file=$files[$i];

		my %sample=();		# alle samples im aktuellen genotypen file: sample{spalte}=sampleID
		my $c1=0;	# all SNP-lines in infile
		my $c2=0;	# SNPs not skipped
		my @sam=();	# Spalten-nummer in der ein "_Call" steckt
		my $c_sam=0;
		my $c_snp=0;	# Spalte mit SNP ID
		my $pid="";
		my $gtyp="";
		my $schalt=0;	# Header line processed = 1 #
		
		print "Read genotypefile\t: $file";
		ShowOutput("Read genotypefile : $file\n");
		open (IN, "$file") || die "could not open genotypefile $file :$!\n";
LINE5:	while (<IN>){
			next LINE5 if /^$/;
			next LINE5 if /^#/;
#			next LINE5 if /^AFFX/;
			chomp;
			if ($schalt == 0 and ($_ =~ /SNP ID/)||($_ =~ /SNP_ID/)||($_ =~ /probeset id/)) {
				@head=split('\t',$_);
				for (my $z=0;$z<=$#head;$z++) {	# parse header line
					if (($head[$z] eq "SNP ID") ||($head[$z] eq "SNP_ID")||($head[$z] eq "probeset id")){$c_snp=$z;}			
					elsif ($head[$z] =~ /_Call/) {	#
						$head[$z] =~ s/_Call//;

						my @feld=split($FS,$head[$z]);	  ### GMC Trennzeichen
						if ($#feld > 1) {
							$pid=$feld[2];
							$sample{$z}=$pid;
							$allsamples{$pid}++;
						}  ############### SampleID in 3th field
						else {
							$pid=$feld[0];
							$sample{$z}=$pid;
							$allsamples{$pid}++;
						}	# Hash SampleID in Spalte $z #
						push (@sam, $z);
					}				
	 				else { print "\t$head[$z] not used\n"; }
				}
				$schalt= 1;
				next LINE5;
			}
			if ($schalt ==1) {
				s/NoCall/NC/g;
				s/NN/NC/g;
				my @v=split('\t',$_);
				if ($v[$c_snp] eq "") {next LINE5;}	# no SNP_ID
				$c1++;

				my $snp=$v[$c_snp];
				
				if (exists $skiplist{$snp}) { $skipped{$snp}++; next LINE5;}	# don't read in this SNPs

				$allmarkers{$snp}++;

				foreach my $col (@sam) {				# Create hash genotypes
					my $pid=$sample{$col};
					$gtyp=$v[$col];
					if (($gtyp eq "NC")||($gtyp eq "-1")) { $nc{$snp}++; $nocall{$pid}++;}
					if (($gtyp eq "NC")||($gtyp eq "AA")||($gtyp eq "A")||($gtyp eq "0")) {$AA{$snp}++;}
					if (($gtyp eq "NC")||($gtyp eq "BB")||($gtyp eq "B")||($gtyp eq "2")) {$BB{$snp}++;}
					if (($gtyp =~ /A|B|H|0|2/) ||($gtyp eq "1")) { $SampleCalls{$pid}++; }
				}
				$c2++;
			}
		}
		close (IN);
		
		my $c_samples=$#sam +1;
		print "\t$c_samples samples\n";
	
		my $c3=$c1-$c2;
		ShowOutput("\t$c_samples samples; $c2 of $c1 SNPs read in, $c3 skipped\n");
	}

	my $nr = (keys %allsamples);
	
	print "\nTotal number of samples:  $nr\n";
	ShowOutput("\nTotal number of samples:  $nr\n");
	
	my $sum = (keys %allmarkers);
	print "Total number of markers for calculation: $sum\n";
	ShowOutput("Total number of markers for calculation: $sum\n");
	
	my $sk =(keys %skipped);
	print "Total number of markers skipped: $sk\n";
	ShowOutput("Total number of markers skipped: $sk\n");


################################################################################ neu ###  	
	foreach my $snp (keys %allmarkers) {	# for every SNP

		### add up all NoCalls from all SNPs
		$c_nocalls += $nc{$snp};

		if ($nc{$snp} == $nr){push (@allhomozygote,$snp);next;}
		if ($AA{$snp} == $nr){push (@allhomozygote,$snp);next;}
		if ($BB{$snp} == $nr){push (@allhomozygote,$snp);}
	}


	my $calls=0;
	my $rate=0.0;
	my $var=@allhomozygote;
	
	open (OUT,"> $statfile") || die "could not open $statfile :$!\n";

	print OUT "Total number of genotyped samples:  $nr\n";
	print OUT "Total number of markers for calculation: $sum\n";
	print OUT "Total number of markers skipped: $sk\n";
	
	my $ngtyps=$nr * $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}\%\n");	
	print OUT "Callrate over all: ${proz}\%\n";

	$proz=sprintf("%5.2f",($var*100/$sum));
	ShowOutput("SNPs not informative : $var \($proz \%\) of $sum markers\n");
	print OUT "SNPs not informative : $var \($proz \%\) of $sum markers\n";

	print OUT "\nCalling rate by sample:\n";
	foreach my $pid (keys %allsamples) {		# for each sample
		$calls=$sum-$nocall{$pid};
		$rate=sprintf("%5.3f",$calls/$sum);
		my $xsum=$nocall{$pid} + $SampleCalls{$pid};
		my $xrate=sprintf("%5.3f",$SampleCalls{$pid}/$xsum);
		print OUT "Calls sample $pid : $calls \($rate\) of $sum ; RealCalls:\t$SampleCalls{$pid}\tRealCallRate:\t$xrate\n";
	}
	
	close (OUT);
	ShowOutput("\nWrite file        : $statfile\n");
	
	open (OUT,"> $not_inf_file") || die "could not open not $not_inf_file :$!\n";
	print OUT "# Non-informative markers list: In $sams samples of the current data set only one allele or/and NoCalls appeared\n";
	keys (%allhomoz) = $var;
	foreach (@allhomozygote) {
		print OUT "$_\n";
		$allhomoz{$_}=1;
	}
	close (OUT);
	ShowOutput("Write file        : $not_inf_file\n");

	ShowOutput("\nCalculate calling rate done\n");
	print "\nCalculate calling rate done\n\n";
	$statusstat=1;
}


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

	if ($statusgtyphdr == 0) {
		ShowOutput("No data loaded!\nPlease enter genotypefile and read files!\n");
		return;
	}
	
	my $minor =0; 
	my ($anzA, $anzB, $sum, $AA, $AB, $BB, $NC, $freqA, $freqB);
	my $max=0;
	my $notinf=0; 
	my $hetexp=0;
	my $hetobs=0;
	@snplist=@autolist;
	push (@snplist,@nokoordlist);
	my $var=$#snplist+1;
	my $NA=0;
	my $gf;
	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 all genotyped founders
			}
		}
	}
	else { 
		$sample_set = "founders only";
		foreach my $pid (@founder) {	# how much founders are genotyped?
			if (exists $samples{$pid}){
				push (@gsamples,$pid);	# select all genotyped 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");	
	###--- end select samples ---###

	$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-----##
	for (my $anz=0;$anz<=$#snplist;$anz+=$loadsize) {#  jeweils $loadsize SNPs nachladen
		my $max = $anz + $loadsize;
		my $anz1=$anz+1;
		if ($max > $#snplist) { $max = $#snplist +1;}
		print "Subset: $anz1 - $max\n";
		%choice = ();
		keys (%choice)=($loadsize);
		for (my $i=$anz;$i<$max;$i++) {
			$choice{$snplist[$i]}=1;		# selection for ReadGenotypeFile
		}
		%gtype=();
		my $nr= (keys %samples);
		keys (%gtype)=($nr * $loadsize);			
	  	ShowOutput("\nLoad data $anz1 - $max\n");
		ReadGenotypeFile();
		if ($del_errors == 1) {&DelErrors;}
		if ($del_unlikely == 1) {&DelUnlikely;}

		for (my $k=$anz;$k<$max;$k++) {
			$AA=0; $BB=0; $AB=0; $NC=0;
			foreach my $pid (@gsamples) {
				if (($gtype{$pid}{$snplist[$k]} eq "AA")||($gtype{$pid}{$snplist[$k]} eq "0")) {$AA++;}
				elsif (($gtype{$pid}{$snplist[$k]} eq "BB")||($gtype{$pid}{$snplist[$k]} eq "2")) {$BB++;}
				elsif (($gtype{$pid}{$snplist[$k]} eq "AB")||($gtype{$pid}{$snplist[$k]} eq "1")){$AB++;}
				else {$NC++;}
			}
			$anzA=((2*$AA) + $AB);
			$anzB=((2*$BB) + $AB);
			$sum=$anzA+$anzB;
			$var=$gf - $NC;	# genotyped founder
			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 ("%s\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",$snplist[$k],$freqA,$freqB,$minor,$hetexp,$hetobs,$AA,$AB,$BB,$NC,$var,$rate,$chi2);
			}
			else {$NA++;
				printf OUT ("%s\t----\t----\t----\t----\t----\t%3d\t%3d\t%3d\t%3d\t%4d\t%4.3f\t----\n",$snplist[$k],$AA,$AB,$BB,$NC,$var,$rate);
			}
		}
	}

	##----- x-linked -----##
	open (OUT2,"> X-freqs.txt") || die "could not open X-freqs.txt :$!\n";
	@snplist=();
	push (@snplist, @xlist);
	$var=$#snplist+1;
	print "\n x-linked\t$var marker\n";	
	ShowOutput("\n x-linked\t$var marker\n");	
	
	for (my $anz=0;$anz<=$#snplist;$anz+=$loadsize) {#  jeweils $loadsize SNPs nachladen
		my $max = $anz + $loadsize;
		my $anz1=$anz+1;
		if ($max > $#snplist) { $max = $#snplist +1;}
		print "Subset: $anz1 - $max\n";
		%choice = ();
		keys (%choice)=($loadsize);
		for (my $i=$anz;$i<$max;$i++) {
			$choice{$snplist[$i]}=1;		# selection for ReadGenotypeFile
		}
		%gtype=();
		my $nr= (keys %samples);
		keys (%gtype)=($nr * $loadsize);			
	  	ShowOutput("\nLoad data $anz1 - $max\n");
		ReadGenotypeFile();	
		if ($del_errors == 1) {&DelErrors;}
		if ($del_unlikely == 1) {&DelUnlikely;}
		
		for (my $k=$anz;$k<$max;$k++) {
			$AA=0; $BB=0; $AB=0; $NC=0; $anzA=0; $anzB=0;
			foreach my $pid (@gsamples) {
				if ( $gender{$pid} == 2) {
					if (($gtype{$pid}{$snplist[$k]} eq "AA")||($gtype{$pid}{$snplist[$k]} eq "0")) { 
						$AA++;
						$anzA++;$anzA++;
					}
					elsif (($gtype{$pid}{$snplist[$k]} eq "BB")||($gtype{$pid}{$snplist[$k]} eq "2")) {
						$BB++;
						$anzB++;$anzB++;
					}
					elsif (($gtype{$pid}{$snplist[$k]} eq "AB")||($gtype{$pid}{$snplist[$k]} eq "1")) {
						$AB++;
						$anzA++;$anzB++;
					}
					else {$NC++;}
				}
			}
		
			$sum=$anzA+$anzB;
			$gf=$AA + $AB + $BB + $NC;
			$var=$gf - $NC;	# genotyped founder
			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",$snplist[$k],$freqA,$freqB,$minor,$hetexp,$hetobs,$AA,$AB,$BB,$NC,$var,$rate,$chi2);
				printf OUT2 ("%-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",$snplist[$k],$freqA,$freqB,$minor,$hetexp,$hetobs,$AA,$AB,$BB,$NC,$var,$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",$snplist[$k],$AA,$AB,$BB,$NC,$var,$rate);}
		}
	}	

	##----- end x-linked -----##

	close (OUT2);
	close (OUT);
	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"); }
	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 "del_unlikely") {$del_unlikely=$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 "skip_nopos") {$skip_nopos=$z[1];}
		elsif ($z[0] eq "skip_errors") {$skip_errors=$z[1];}
		elsif ($z[0] eq "skip_notinf") {$skip_notinf=$z[1];}
		elsif ($z[0] eq "skip_list") {$skip_list=$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 "load_size") {$loadsize=$z[1];}
		elsif ($z[0] eq "field_separator") {$FS=$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 "GW6_map_deCode") {$decode_map_gw6=$z[1];}
		elsif ($z[0] eq "GW6_map_Marshf") {$marshf_map_gw6=$z[1];}
		elsif ($z[0] eq "GW6_map_SLM1") {$slm1_map_gw6=$z[1];}
		elsif ($z[0] eq "GW6_map_Other") {$other_map_gw6=$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];}
#tim
		elsif ($z[0] eq "Illumina300k_map_deCode") {$decode_map_illumi300k=$z[1];}
		elsif ($z[0] eq "Illumina300k_map_Marshf") {$marshf_map_illumi300k=$z[1];}
		elsif ($z[0] eq "Illumina300k_map_SLM1") {$slm1_map_illumi300k=$z[1];}
		elsif ($z[0] eq "Illumina300k_map_Other") {$other_map_illumi300k=$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 "GW6_freqA_afam") {$freq_afam_gw6=$z[1];}
		elsif ($z[0] eq "GW6_freqA_asian") {$freq_asian_gw6=$z[1];}
		elsif ($z[0] eq "GW6_freqA_caucasian") {$freq_cauc_gw6=$z[1];}
		elsif ($z[0] eq "GW6_freqA_Other") {$freq_other_gw6=$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];}		
#tim
 		elsif ($z[0] eq "Illumina300k_freqA_afam") {$freq_afam_illumi300k=$z[1];}
		elsif ($z[0] eq "Illumina300k_freqA_asian") {$freq_asian_illumi300k=$z[1];}
		elsif ($z[0] eq "Illumina300k_freqA_caucasian") {$freq_cauc_illumi300k=$z[1];}
		elsif ($z[0] eq "Illumina300k_freqA_Other") {$freq_other_illumi300k=$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 "load_size\=$loadsize	\# load genotypes dynamicly in portions of markers\n";
	print OUT "field_separator\=$FS		\# field separator in experiment 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 structure and affection status\n";
	print OUT "skiplist_file\=$skipfile		\# file containing SNPs to omit\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 "GW6_map_deCode\=$decode_map_gw6	\# GW6\n";
	print OUT "GW6_map_Marshf\=$marshf_map_gw6\n";
	print OUT "GW6_map_SLM1\=$slm1_map_gw6\n";
	print OUT "GW6_map_Other\=$other_map_gw6\n";

	print OUT "Illumina_map_deCode\=$decode_map_illumi	\# e.g.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";
#tim
	print OUT "Illumina300k_map_deCode\=$decode_map_illumi300k	\# Illumina 300K\n";
	print OUT "Illumina300k_map_Marshf\=$marshf_map_illumi300k\n";
	print OUT "Illumina300k_map_SLM1\=$slm1_map_illumi300k\n";
	print OUT "Illumina300k_map_Other\=$other_map_illumi300k\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 "GW6_freqA_afam\=$freq_afam_gw6\n";
	print OUT "GW6_freqA_asian\=$freq_asian_gw6\n";
	print OUT "GW6_freqA_caucasian\=$freq_cauc_gw6\n";
	print OUT "GW6_freqA_Other\=$freq_other_gw6\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";
#tim
	print OUT "Illumina300k_freqA_afam\=$freq_afam_illumi300k\n";
	print OUT "Illumina300k_freqA_asian\=$freq_asian_illumi300k\n";
	print OUT "Illumina300k_freqA_caucasian\=$freq_cauc_illumi300k\n";
	print OUT "Illumina300k_freqA_Other\=$freq_other_illumi300k\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;
	$statusmap=0;
	$statusfreq=0;
	$status_skiplist=0;
	$$status_PedCheckErr=0;
}

############################  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,@_);
}

########################  ERRORMSG  ###################

sub Errormsg {
	if ($command_line == 1) {
		foreach (@_) {
			print "$_\n";
		}
	}
	else {

		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_M $version");
 $MW2->Label(-text=>"ALOHOMORA\n\nOPENS THE DOOR\nfrom SNP Array to Linkage Analysis\n\nSNP Array Quality Control and Data Conversion\n\nALOHOMORA_M $version\nslow version for Mega chips\n\n(c) 2003-2010 Franz Rschendorf\n\nMax-Delbrck-Center for Molecular Medicine, Berlin",-width=>60,-height=>14)->pack;
 $MW2->Button(-text=>"OK",
             -width=>8,-height=>1,-command=>sub{destroy $MW2;})->pack;
 MainLoop;
}

#################     ###################

sub MW2LinkageFiles {
if ($command_line == 1) { &MakeLinkageFiles; }
else {
 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 ($skip_notinf == 1) {		# Skip not informative SNPs
		if ($statusstat == 0) {
			if (! -f $not_inf_file) {&CallingRate;}
			else { &ReadNotInf;}
		}
	}

	print "Section MakeLinkageFiles SUBSETS = $subset\n";
	if ($subsets == 0) {		
		if ($qtl_select == 1) {$targetdir="${selection}_qtl";}
		else {$targetdir=$selection;}
		if (! -d $targetdir) { mkdir ($targetdir,0777); ShowOutput("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");}
		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'); 
 }
#----------- GW6 ---
 elsif ($chip eq "GW6") {
 $f1->Label(-text => "Afro Americans",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e1=$f1->Entry(-width=>50, -textvariable=> \$freq_afam_gw6)->pack(-side => 'right');
 my $b1_f1 = $f1->Button(-text => "Browse",
			-command=>sub{$freq_afam_gw6=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_gw6)->pack(-side => 'right');
 my $b1_f2 = $f2->Button(-text => "Browse",
			-command=>sub{$freq_asian_gw6=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_gw6)->pack(-side => 'right');
 my $b1_f3 = $f3->Button(-text => "Browse",
			-command=>sub{$freq_cauc_gw6=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_gw6)->pack(-side => 'right');
 my $b1_f4 = $f4->Button(-text => "Browse",
			-command=>sub{$freq_other_gw6=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_gw6)->pack(-side => 'right');
 my $b1_f5 = $f5->Button(-text => "Browse",
			-command=>sub{$decode_map_gw6=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_gw6)->pack(-side => 'right');
 my $b1_f6 = $f6->Button(-text => "Browse",
			-command=>sub{$marshf_map_gw6=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_gw6)->pack(-side => 'right');
 my $b1_f7 = $f7->Button(-text => "Browse",
			-command=>sub{$slm1_map_gw6=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_gw6)->pack(-side => 'right');
 my $b1_f8 = $f8->Button(-text => "Browse",
			-command=>sub{$other_map_gw6=FileDialog("Select other map file $chip")})->pack(-side => 'right'); 
 }
# ----------- 
 elsif ($chip eq "Illumina") {
 $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'); 
 } 
 #tim
 elsif ($chip eq "Illumina300k") {
 $f1->Label(-text => "Afro Americans",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 my $e1=$f1->Entry(-width=>50, -textvariable=> \$freq_afam_illumi300k)->pack(-side => 'right');
 my $b1_f1 = $f1->Button(-text => "Browse",
			-command=>sub{$freq_afam_illumi300k=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_illumi300k)->pack(-side => 'right');
 my $b1_f2 = $f2->Button(-text => "Browse",
			-command=>sub{$freq_asian_illumi300k=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_illumi300k)->pack(-side => 'right');
 my $b1_f3 = $f3->Button(-text => "Browse",
			-command=>sub{$freq_cauc_illumi300k=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_illumi300k)->pack(-side => 'right');
 my $b1_f4 = $f4->Button(-text => "Browse",
			-command=>sub{$freq_other_illumi300k=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_illumi300k)->pack(-side => 'right');
 my $b1_f5 = $f5->Button(-text => "Browse",
			-command=>sub{$decode_map_illumi300k=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_illumi300k)->pack(-side => 'right');
 my $b1_f6 = $f6->Button(-text => "Browse",
			-command=>sub{$marshf_map_illumi300k=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_illumi300k)->pack(-side => 'right');
 my $b1_f7 = $f7->Button(-text => "Browse",
			-command=>sub{$slm1_map_illumi300k=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_illumi300k)->pack(-side => 'right');
 my $b1_f8 = $f8->Button(-text => "Browse",
			-command=>sub{$other_map_illumi300k=FileDialog("Select other map file $chip")})->pack(-side => 'right'); 
 }
  else { ErrorMsg ("unknown Enzym selection");}



 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 $f6 = $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 9000 informative markers are enough.\n",
 	-font=>'Arial 10 normal')->pack(-side =>'top',-anchor => 'n');
 $f2->Label(-text => "Example: Select markers every 300000 bases\n and with a minor allele freqency >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');
 $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  L O A D  G T Y P E   F I L E S  ##################### 

sub MW8LoadDataMode {
 
 my $MW8=MainWindow->new();
 $MW8->title("Options for load genotype data");

 my $f0 = $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 $f9 = $MW8->Frame->pack(-side=>'top',-fill=>'x');

 $f0->Label(-text => "\nRestrict number of markers loaded from genotype data files",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'n');

 $f2->Label(-text => "Loading all genotype data from all markers\nmay exceed your computers main memory.\nTherefore restrict number of markers loaded at the same time.\n",
 	-font=>'Arial 10 normal')->pack(-side =>'top',-anchor => 'n');
 $f2->Label(-text => "Examples: Loading 10000 markers from 1000 samples\nwill need ~720MB RAM",
 	-font=>'Arial 10 normal')->pack(-side =>'top',-anchor => 'n');
 $f2->Label(-text => "This value only affects the work flow of Alohomora\n",
 	-font=>'Arial 10 normal')->pack(-side =>'top',-anchor => 'n');

 $f3->Label(-text => "max number of markers",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 $f3->Entry(-width=>20, -textvariable=> \$loadsize)->pack(-side => 'right');

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

#######################  M W 9  F I E L D  S E P A R A T O R  ################## 

sub MW9FS {
 
 my $MW9=MainWindow->new();
 $MW9->title("Options for field separator");

 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');
 my $f3 = $MW9->Frame->pack(-side=>'top',-fill=>'x');
 my $f4 = $MW9->Frame->pack(-side=>'top',-fill=>'x');
 my $f5 = $MW9->Frame->pack(-side=>'top',-fill=>'x');
 my $f6 = $MW9->Frame->pack(-side=>'top',-fill=>'x');
 my $f9 = $MW9->Frame->pack(-side=>'top',-fill=>'x');

 $f0->Label(-text => "\nSelect field separator to identify sample ID in experiment name",-font=>'Arial 12 normal',-foreground=>'Blue')->pack(-side =>'top', -anchor =>'n');

 $f2->Label(-text => "Columns containing genotype calls are identified\nby a ending \'_Call\' in the column header.\nExample for experiment name: vvv-www-xxx-yyy-zzz_Call\n",
 	-font=>'Arial 10 normal')->pack(-side =>'top',-anchor => 'n');
 $f2->Label(-text => "Alohomora cuts the \'_Call\' and splits the rest by a field separator \(FS\).\nIf FS is \'-\' then the third field \'xxx\' is selected as sampleID.\n",
 	-font=>'Arial 10 normal')->pack(-side =>'top',-anchor => 'n');
 $f2->Label(-text => "If the FS is something else then the whole string \"vvv-www-xxx-yyy-zzz\"\nis the sampleID, which connects the genotypes with the samples in the pedigree file.\n",
 	-font=>'Arial 10 normal')->pack(-side =>'top',-anchor => 'n');

 $f3->Label(-text => "Field separator",-font=>'Arial 10 normal',-foreground=>'red3')->pack(-side =>'left');
 $f3->Entry(-width=>20, -textvariable=> \$FS)->pack(-side => 'right');

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

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

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

 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');
 my $f3 = $MW10->Frame->pack(-side=>'top',-fill=>'x');
 my $f4 = $MW10->Frame->pack(-side=>'top',-fill=>'x');
 my $f5 = $MW10->Frame->pack(-side=>'top',-fill=>'x');
 my $f6 = $MW10->Frame->pack(-side=>'top',-fill=>'x');
 my $f7 = $MW10->Frame->pack(-side=>'top',-fill=>'x');
 my $f8 = $MW10->Frame->pack(-side=>'top',-fill=>'x');
 my $f9 = $MW10->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 $MW10;})->pack(-side => 'left',-anchor =>'n');
 $f9->Button(-text=>"Cancel", -width=>10,-height=>1,
			-command=>sub{destroy $MW10;})->pack(-side => 'right',-anchor =>'n');
 $MW10->focusForce;
 MainLoop;
}

###########################  M W 9  A L I A S  N A M E S  ###################### 
sub MW12Alias {
 
	my $MW12=MainWindow->new();
	$MW12->title("Alias name");
	my $f0 = $MW12->Frame->pack(-side=>'top',-fill=>'x');
	my $f1 = $MW12->Frame->pack(-side=>'top',-fill=>'x');
	my $f2 = $MW12->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 $MW12;})
				->pack(-side => 'top');
 MainLoop;
}

##################  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;
	}

}

########################  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;
	}
	my $aref1;

	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";}

	### select position	
	if ($select_pos == 1) {
		ShowOutput( "\tchromosome: $mschrom\n\tfirst position: $firstmspos\n\tlast position: $lastmspos\n");

		foreach (@koord) {	# select SNPs from genetic map with high minor allele frequency
			my ($chrom,$marker,$genpos,$physpos,@rest)=split('\t',$_);
			if (	exists $skiplist{$marker}) {next;};
			if (($chrom eq "$mschrom") && ($physpos > $firstmspos) && ($physpos < $lastmspos)) {
				push (@maptmp,$_);
			}
		}
		$aref1=\@maptmp;
	}
	else {$aref1=\@koord;}


	### select distance
	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 (@$aref1) {	# 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;
}


##########  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');
	}
  	$f1->Label(-text=>"", -font=>'Arial 10 normal',-width=>10,-height=>1)->pack;

	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.2
# 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 $affson=0;	# affected male non-founder
	my $affdau=0;	# affected female non-founder

	my $mafound=0;	# male founder
	my $fefound=0;	# female founder
	my $cson=0;		# number of male non-founders
	my $cdau=0;		# number of female 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(' ',$_);
		}
		
		##---------- 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 ne "0") && ($sex == 1)) { $affson++; }
			if (( $dad ne "0") && ($sex == 2)) { $affdau++ }
			$affinfam++;
			$affpers++; 
		}

		if ($aff == 1) { $naff++; }
		if ($aff == 0) { $unknown++; }
		if (( $dad eq "0") && ($sex == 1)) { $mafound++; }
		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") && ($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;
	my $aff_nfound = $affson + $affdau;
	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));
	ShowOutput(sprintf("affected male   non-founder   : %4s \n",$affson));
	ShowOutput(sprintf("affected female non-founder   : %4s \n\n",$affdau));

	ShowOutput(sprintf("total male   founder          : %4s \n",$mafound));
	ShowOutput(sprintf("total female founder          : %4s \n",$fefound));
	ShowOutput(sprintf("total male   non-founder      : %4s \n",$cson));
	ShowOutput(sprintf("total female non-founder      : %4s \n\n",$cdau));
	
	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_M $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);

}

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

sub GetArguments {
	GetOptions(
		"p=s" => \$pedfilepro,
		"g=s" => \$infile,
		"b=s" => \$batch_file,
		"nogui" => \$command_line,
		"help|?|h" => \$clhelp
	);
}

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

sub CommandLineHelp {
	print "\nALOHOMORA_M $version\n";
	print "(c) 2003-2009 Franz Rschendorf\n";
	print "\nusage: alohomora_M [<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";
}
#############################   D R U C K E N    ###############################

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

############################   S P E I C H E R N   ##############################

sub Savefile {
	$outfile="alohomora.log";
	if (-f $outfile) { move ($outfile,"${outfile}0");}
	open (FH, "> $outfile");
	foreach (@alog) {	print FH "$_"; }
	close (FH);
	print "Window saved in $outfile!\n";
#	if ($command_line == 0) {
#		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\.log";
	open (FH, "> $outfile");
	foreach (@alog) { print FH "$_"; }
	close (FH);
}

#############################   B E E N D E N    ###############################

sub Quit {
	&Savefile;
	if ($command_line == 0) {$mw->destroy;}
	exit 0;
}


####################################  Test  ####################################
sub Test {
	print "Infile: $infile\n";
	my @files=glob("$infile");	# alle Genotypenfiles im Affy Format

	for (my $i=0;$i<=$#files;$i++) {		# fr jeden Infile
		my $file = $files[$i];
		print "$i : $file\n";
	}
}

#################################   E N D E   ##################################



__DATA__

========================
ALOHOMORA_M v0.33 HELP
========================

  M for Mega chips


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

  ALOHOMORA_M 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 500K Array.
  
  ALOHOMORA_M combines information about pedigree structure, affection status,
  marker allele frequencies, genetic or 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 different 
  ethnicities (African American, Asian and Caucasian) can optionally be selected
  by the user (data from the Affymetrix SNPannotation 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 analysis results can be plotted with the help
  of Perl-scripts and Gnuplot.


================================================================================
DIFFERENCES TO PREVIOUS RELEASES OF ALOHOMORA
================================================================================

  The number of genotype data files is not restricted.
  The genotype data files are specified with a wild-card (e.g. TableData_*.txt).
  ALOHOMORA_M reads and processes the input genotype data with a sliding window.
  The size of the sliding window depends on your computer main memory and is 
  controlled by the variable "load_size" in the alohomora.ini file. 
  Load_size restricts the number of markers loaded into the computers RAM at the 
  same time. This makes ALOHOMORA_M to be nearly unlimited to the number of 
  genotypes, but it makes the workflow much slower than in ALOHOMORA.
  
  The format of the genotype data file has changed! Now original GTYPE or GDAS
  output files will be loaded. The column containing the marker name is 
  identified by the column header "SNP ID" and all columns containing genotypes 
  must have an ending "_Call" in their header. There may be additional 
  columns, not being the marker name or genotypes, in this file. 
   
  

================================================================================
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, A or 0 for homozygote on the first allele,
  BB, B or 2 for homozygote on the second allele and AB or 1 for heterozygote.
  Valid values for a missing genotype is NoCall, NC or -1.

  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_Call	2213_Call	...
   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
================================================================================

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 a allele frequency file
  estimated from the data set.
  To make changes permanent use in the pull-down menu
    Menu -> Utilities -> Save current environment
  this creates the file alohomora.ini.
  


Start Alohomora_M in Batch-mode:
----------------------------------

  usage: alohomora_M --nogui [<options>] 
  options:
     --nogui              command line 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 alohomora_M is started with the option --nogui it reads at first 
  the file alohomora.ini and then, if available, alohomora.bch, the file
  containing the commands.


================================================================================
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 RUESCHENDORF, 31-Jul-2009

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