#!/usr/bin/php
<?php
Class ALN2FAS
{
    var 
$aln;
    var 
$file;
    var 
$fastafile;
    var 
$start;
    var 
$end;
    
    public function 
__Construct()
    {

        
$this->aln=file_get_contents($this->getInput("Drag your ALN file here >>"));
        
$this->start=$this->getInput("Start Position ?")-1;
        
$this->end=$this->getInput("End Position ?")-1;
        
$outfile=$this->getInput("Name of Outputfile (without extention)");
        
$this->build();
        
$this->write();
        
system("mv /tmp/fastalol.faa ~/Desktop/$outfile.txt");
        
system("open ~/Desktop/$outfile.txt");
    }
    
    public function 
build()
    {
        
$pattern='/[A-Z0-9]{1,7}\s+[A-Z,-]{60}/i';
        
preg_match_all($pattern,$this->aln,$out,PREG_PATTERN_ORDER);
        foreach(
$out[0] as $res)
        {
            
$res=preg_split('/\s+/',$res);
            
$seq[$res[0]][]=$res[1];
        }
        foreach(
$seq as $symbol=>$s)
        {
            
$seq=preg_replace("/[^A-Z]/i",NULL,implode(NULL,$s));
            unset(
$seg);
            for(
$i=$this->start;$i<=$this->end;$i++)
            {
                @
$seg.=$seq[$i];
            }
            
$final[$symbol]=$seg;
        }
        
$this->aln=$final;
    }
    
    public function 
getInput($msg)
    {
        
fwrite(STDOUT"$msg: ");
        
$varin trim(fgets(STDIN));
        return 
$varin;
    }
    
    public function 
write()
    {
        
$handle=fopen("/tmp/fastalol.faa","w+");
        foreach(
$this->aln as $symbol=>$seg)
        {
            
$fastas[]=">$symbol\n$seg";
        }
        
$fastas=implode("\n",$fastas);
        
fwrite($handle,$fastas);
    }
    
}
new 
ALN2FAS;
?>