package Misc;

use warnings;
use strict;





use File::Find;

# Example
#  Misc::findNameInit(".hmtl");
#  my @p0=Misc::findnameEval();

my $findname_ext="";
my @findname_files=();

sub findname
{
  if (/$findname_ext$/)
  {
    push @findname_files, $File::Find::name;
  }
}

# Constructor
# 1: Extension
sub findnameInit
{
  $findname_ext=shift;
  @findname_files=();
}

# Return: list of files found.
sub findnameEval
{
  find(\&findname,'.');
  return @findname_files;
}

# Return: list of files found.
sub findnameEvalParent
{
  find(\&findname,'..');
  return @findname_files;
}

sub findnamePrint
{
  my $file;
  foreach $file (@findname_files)
  {
    printf "%s\n",$file;
  }
}


# Trim the start and end space of a string.
# 1:  string to trim
sub trim 
{
  my($string)=@_;
  for ($string) 
  {
    s/^\s+//;
    s/\s+$//;
  }
  return $string;
}

# Generalizes trim, so start and end are supplied as arguemnts.
# 1: target string
# 2: left end pattern match
# 3: right end pattern match
# Return value is the new string.
# Example
#   $s2 = Misc::trimends($s1,"\/","\/");
sub trimends
{
  my $s1=shift;
  my $a0=shift;
  my $a1=shift;

  for ($s1)
  {
    s/^$a0//;
    s/$a1$//;
  }

  return $s1;
}

# Overwrite the file with the string.
# 1: filename
# 2: string
sub fileoverwrite
{
  my $file=shift;
  my $str=shift;

  if (-e $file)
    { unlink $file or die "error:  can not delete $file\n"; };

  if (! open FILE, ">".$file )
    { die "error:  could not open $file\n"; };

  select FILE;
  printf "%s",$str;
  select STDOUT;
  close FILE;
}

# Find path to base directory.
# 1: path  eg ./p1/tasks/report.html
# Return relitive path eg ../.. for ./p1/tasks/report.html
sub pathtobasedir
{
  my $path=shift;

  my @x1=split(/\//,$path);
  my $sz = scalar @x1;
  if ($sz == 2)
    { return "./"; };
  if ($sz < 2)
    { die "error: ".$path." is not a path\n"; };

  my $path2="";
  $sz = $sz-2;
  for (1 .. $sz)
    { $path2=$path2."../"; };

  return $path2;
}


1;

