#!/usr/bin/perl

use strict;
use warnings;

if ($#ARGV != 2) {
    print "usage: fasta_split_by_header_regex.pl input_fasta output_file regex_pattern\n";
    exit;
}

my $infile = $ARGV[0];
my $outfile = $ARGV[1];
my $regex = $ARGV[2];

my $line_is_header = 0;
my $header_matches_regex = 0;

open(INFILE, "$infile") or die "Error opening input file!\n";

open(OUTFILE, ">$outfile") or die "Error opening output file!\n";

while(my $line = <INFILE>) {
    chomp $line;

    if ($line =~ /^>/) {
        $line_is_header = 1;
        $header_matches_regex = 0; # reset for new header line
        if ($line =~ /$regex/) {
            $header_matches_regex = 1;
            print OUTFILE "$line\n";
        }
    }else{
        $line_is_header = 0;
        if ($header_matches_regex) {
            print OUTFILE "$line\n";
        }
    }
}

close(INFILE);
close(OUTFILE);