#! /usr/bin/perl -w

# -- PB User Script Info --
# %%%{PBXName=Place Protocol Method Skeletons on Clipboard}%%%
# %%%{PBXInput=AllText}%%%
# %%%{PBXOutput=Pasteboard}%%%
# %%%{PBXKeyEquivalent=~i}%%%
#

use strict;

$/=undef; #Need the whole file at once, break it up later

my $fullText = <>; #Get the whole source file
$/="\n";
my @lines = split("\n",$fullText); #Now break the file by line breaks
my $selstart = %%%{PBXSelectionStart}%%%;
my $sellen = %%%{PBXSelectionLength}%%%;
#print "Start: " . $selstart . "\n";
#print "Len: " . $sellen . "\n";
my $selection = substr($fullText,$selstart,$sellen); #Grab the selection
my $stidx=-1; #protocol starts here
my $endidx=-1; #protocol ends here
my $x=-1;
chomp($selection);
for($x=0;$x<@lines;$x++) { #Search the lines for start and end of protocol
    if(index($lines[$x],$selection) >= 0) {
      if(index($lines[$x],'@protocol') >= 0) {
        $stidx=$x;
      }
    }
    if($stidx != -1 && index($lines[$x],'@end') >= 0) {
      $endidx=$x;
      last;
    }
}
if($endidx == -1 || $stidx == -1) { #If selection is not a protocol
  exit;
}
my $semi=";";
my @protocoldef = split(" +",$lines[$stidx]);
my $protocol = $protocoldef[1];
for($x=$stidx+1;$x<$endidx;$x++) { #Print every line
  my $replace=" {\n  //Implement this to complete " . $protocol . "\n}\n";
  $lines[$x] =~ s/$semi/$replace/; #If the line has a semicolon, insert function def. instead.
  print $lines[$x] . "\n";
}
