generate_solution.pl 31.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
#!/usr/bin/perl

#
# Copyright:2012-2015 Jan Silovsky
#           2015 Johns Hopkins University (Author: Jan "Yenda" Trmal <jtrmal@gmail.com>)

# Licence: Apache 2.0
# Copyright Jan Silovsky.
# Modifications and small bugfixes by Jan "Yenda" Trmal

# This program generates the Visual Studio solution file.
# Note, this program has been tested with both cygwin and
# Windows (ActiveState perl) versions of Perl

use strict;
use File::Find;
use File::Path;
use File::Copy;
use FindBin qw($Bin);
use lib "$Bin";
use Data::Dumper;
use Getopt::Long;

my $vsver="vs2017";

my %ENABLED = (CUDA => 0,
               OPENBLAS => 0,
               MKL => 1 );

GetOptions ("vsver=s" => \$vsver,
            "enable-cuda" => \$ENABLED{CUDA},
			"enable-openblas" => sub {$ENABLED{OPENBLAS}=1; $ENABLED{MKL}=0;},
			"enable-mkl" => sub {$ENABLED{OPENBLAS}=0; $ENABLED{MKL}=1;},
			);

my %TOOLS=( default=> "14.1",
            vs2015 => "14.0",
            vs2017 => "14.1"
            );

my %FORMAT=( default=> "14.10",
             vs2015 =>  "14.00",
             vs2017 =>  "14.10"
             );

my %TOOLSET=( default=> "v141",
              vs2015 => "v140",
              vs2017 => "v141"
              );


unless ((defined $TOOLS{$vsver}) && (defined $FORMAT{$vsver}) && (defined $TOOLSET{$vsver})) {
	die "Unknown vsver value: $vsver";
}

my $features_suffix;
my @features_enabled;

if ($ENABLED{OPENBLAS}) {
  push @features_enabled, "OPENBLAS";
}
if ($ENABLED{MKL}) {
  push @features_enabled, "MKL";
}
if ($ENABLED{CUDA}) {
  push @features_enabled, "CUDA";
}

$features_suffix = join("_", @features_enabled);

my $root = "$Bin/..";
my $solutionDir = "$root/kaldiwin_${vsver}_${features_suffix}";
my $projDir = "$solutionDir/kaldiwin";
my $solutionFileName = "kaldiwin_${vsver}.sln";
my $srcDir = "$root/src";


# The following files are in the same dir (windows/) as the
# Perl script.
my @propsFiles = (
  "$Bin/variables.props",
  "$Bin/kaldiwin.props",
  "$Bin/kaldiwin_win32.props",
  "$Bin/openfstwin_debug.props",
  "$Bin/openfstwin_release.props",
  "$Bin/openfstwin_debug_win32.props",
  "$Bin/openfstwin_release_win32.props",
);

my %optionalProps = (
	CUDA => "$Bin/cuda_7.0.props"
	);

# see http://www.mztools.com/Articles/2008/MZ2008017.aspx for list of GUIDs for VS solutions
my $globalGUID = "{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}";  # Windows (Visual C++)

my $projguidListFileName = "$Bin/kaldiwin_projguids.txt";
my $guidgen = "$Bin/NewGuidCmd.exe";  # it is C# application

my $osPathConversion = \&winPath;
if ($^O !~ /MSWin32/i) {
  $osPathConversion = \&unixPath;
}

# function
sub winPath {
  my $path = shift;
  $path =~ s/\//\\/g;
  return $path;
}

# function
sub unixPath {
  my $path = shift;
  $path =~ s/\\/\//g;
  return $path;
}

# function
sub removeStartSlash {
  my $path = shift;
  $path =~ s/^[\\\/]//;
  return $path;
}

sub makeRelPath {
  my $path = winPath(shift);
  my $actual_path = winPath(shift);
  my $relpath = '';

  $path =~ s/\\cygdrive\\(.)\\/$1:\\/;
  $actual_path =~ s/\\cygdrive\\(.)\\/$1:\\/;

  #$path =~ s/[\\\/]+[^\\\/]*$//;
  $actual_path =~ s/[\\\/]+[^\\\/]*$//;

  my @path = split /\\+/, $path;
  my @actual_path = split /\\+/, $actual_path;

  my $i = 0;
  for ($i; $i < @actual_path; $i++) {
    # the zero-length condition may seem ackward, but it solves encountered troubles when two empty string were evaluated as different
    # the case-insensitive comparison is used because of Windows filesystem case-insensitivity
    if (($path[$i] !~ /$actual_path[$i]/i) && (length($path[$i]) > 0) && (length($actual_path[$i]) > 0)) {
      last;
    }
  }
  my $j = $i;
  for ($i; $i < @actual_path; $i++) {
    $relpath .= "..\\";
  }
  for ($j; $j < (@path - 1); $j++) {
    $relpath .= $path[$j] . "\\";
  }
  $relpath .= $path[$j];

  return $relpath;
}

# function
sub checkCRLF {
  my $filename = shift;

  if ($^O =~ /MSWin32/i) {
    print "INFO: function checkCRLF supported only for non-Win environment\n";
    return;
  }

  open(FILE, '<', $filename);
  my @data = <FILE>;
  close(FILE);

  open(FILE, '>', $filename);
  foreach my $line (@data) {
    $line =~ s/(\n|\r\n)$//;
    print FILE $line . "\r\n";
  }
  close(FILE);
}

# function
sub loadHashTxtFile {
  my $filename = shift;
  my $hash = shift;

  open(FILE, '<', &{$osPathConversion}($filename));
  while (my $line = <FILE>) {
    $line =~ s/(\n|\r\n)$//;
    if (my ($key, $value) = $line =~ /^(\S+)\s+(\S+)$/) {
      $hash->{$key} = $value;
    } else {
      print STDERR "ERROR: unable to parse line $line in file $filename\n";
    }
  }
  close(FILE);
}

# function
sub saveHashTxtFile {
  my $filename = shift;
  my $hash = shift;

  open(FILE, '>', &{$osPathConversion}($filename));
  foreach my $key (sort { $a cmp $b } keys %$hash) {
    print FILE $key . "\t" . $hash->{$key} . "\n";
  }
  close(FILE);
}

# function
sub parseMakefile {
  my $makefile = shift;
  my $list = shift;
  my $deps = shift;
  my $libs = shift;

  my $file = $makefile;
  my $path = $file;
  $path =~ s/Makefile$//i;

  open(FILE, '<', &{$osPathConversion}($file));
  my @lines = <FILE>;
  close(FILE);

  my $lines = join '', @lines;
  $lines =~ s/#[^\n]+//g;
  $lines =~ s/\\\s*\n//g;
  if ($ENABLED{CUDA}) {
    $lines =~ s/\n\s*ifeq\s+\(\$\(CUDA\),\strue\)\s*\n\s*OBJFILES\s*\+=\s*([^\n]+)\n\s*endif/\nOBJFILES = \1/gmi
  }
  @lines = split /\n/, $lines;
  #$lines =~ s/\\//g;
  #$lines =~ s/\n/\\/g;
  #print $lines . "\n";
  #@lines = split /\\/, $lines;

  my $aobjects = {};
  my $alibs = {};
  foreach my $line (@lines) {
    $line =~ s/(\n|\r\n)$//;

    if (my ($type, $items) = $line =~ /^\s*(TESTFILES|LIBNAME|BINFILES)\s+=(.+?)$/) {
      #my @items = split /\s+/, $items;
      my @items = $items =~ /(\S+)/g;
      foreach my $item (@items) {
        # $item =~ s/\.a$//i;

        $list->{$type}->{$item} = 1;
        $list->{ALL}->{$item}->{'type'} = $type;
        $list->{ALL}->{$item}->{'path'} = $path;

        if ($type =~ /LIBNAME/) {
          $alibs->{$item} = 1;
        }
      }
    }

    if (my ($items) = $line =~ /^ADDLIBS[^=]*?=(.+?)$/) {
	  my @items = $items =~ /(\S+)/g;

	  foreach my $alib (keys %$alibs) {
		$deps->{$path}->{$alib} = 1;
	  }
      foreach my $item (@items) {
        $item =~ s/^.*[\\\/]//;
        $item =~ s/\.[^\.]*$//;

        $deps->{$path}->{$item} = 1;

      }
    }

    if (my ($type, $items) = $line =~ /^\s*(OBJFILES)\s+=(.+?)$/) {
      my @items = $items =~ /(\S+)/g;
      foreach my $item (@items) {
        $aobjects->{$item} = 1;
      }
    }
  }

  if (scalar keys %{$aobjects} > 0) {
    if (scalar keys %{$alibs} != 1) {
      print STDERR "ERROR: less or more than one libfile, cannot assign aobjects\n";
    } else {
      my $alib = join('', keys %{$alibs}); # $alibs obsahuje nazev pouze jedne knihovny
      foreach my $obj (keys %{$aobjects}) {
        $obj =~ s/\.o$//i;
        $list->{ALL}->{$alib}->{'objs'}->{$obj} = 1;
      }
    }
  }
}

# function
sub makefileFilter {
  if ($_ =~ /Makefile/) { return 1; }
}

# function
sub getProjFileDir {
  my $projname = shift;
  my $projFileName = $projDir . "/$projname";
  return $projFileName;
}

# function
sub writeSolutionFile {
  my $filename = shift;
  my $projlist = shift;
  my $projguids = shift;

  open(SLN, '>', &{$osPathConversion}($filename));
  print SLN
"Microsoft Visual Studio Solution File, Format Version $FORMAT{$vsver}
# Visual Studio 2013
";
  foreach my $projname (sort { $a cmp $b } keys %{$projlist->{ALL}}) {
    if (!exists $projguids->{$projname}) {
      my $cmd = "$guidgen";
      my $guid = `$cmd`;
      $guid =~ s/(\n|\r\n)$//;
      $projguids->{$projname} = uc('{' . $guid . '}');
    }
    my $guid = $projguids->{$projname};
    $projlist->{ALL}->{$projname}->{'guid'} = $guid;
    my $projFileName = winPath(makeRelPath(getProjFileDir($projname), $filename) . "/$projname.vcxproj");
    print SLN
"Project(\"$globalGUID\") = \"$projname\", \"$projFileName\", \"$guid\"
EndProject
";
  }
  print SLN
"Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|x64 = Debug|x64
		Debug|Win32 = Debug|Win32
		Release|x64 = Release|x64
		Release|Win32 = Release|Win32
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
";
  foreach my $projname (sort { $a cmp $b } keys %{$projlist->{ALL}}) {
    my $guid = $projlist->{ALL}->{$projname}->{'guid'};
    print SLN
"		$guid.Debug|Win32.ActiveCfg = Debug|Win32
		$guid.Debug|Win32.Build.0 = Debug|Win32
		$guid.Debug|x64.ActiveCfg = Debug|x64
		$guid.Debug|x64.Build.0 = Debug|x64
		$guid.Release|Win32.ActiveCfg = Release|Win32
		$guid.Release|Win32.Build.0 = Release|Win32
		$guid.Release|x64.ActiveCfg = Release|x64
		$guid.Release|x64.Build.0 = Release|x64
";
  }
  print SLN
"	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
EndGlobal
";
  close(SLN);
}

# function
sub writeProjectFiles {
  my $projname = shift;
  my $projlist = shift;
  my $projdeps = shift;
  my $projlibs = shift;
  my $projguids = shift;

  my $projFileName = winPath(getProjFileDir($projname) . "/$projname.vcxproj");

  my $guid = $projguids->{$projname};
  my $rootnamespace = $projname;
  $rootnamespace =~ s/\W+//g;
  my $srcfiles = {};
  my $conftype = "";

  # set projtype-specific params and add .cc files
  if ($projlist->{ALL}->{$projname}->{'type'} =~ /LIBNAME/) {
    $conftype = "StaticLibrary";

    foreach my $obj (keys %{$projlist->{ALL}->{$projname}->{'objs'}}) {
      my $cfile = winPath($projlist->{ALL}->{$projname}->{'path'} . $obj . '.cc');
	  if (!-e &{$osPathConversion}($cfile)) {
	    if ($ENABLED{CUDA}) {
          my $cufile = winPath($projlist->{ALL}->{$projname}->{'path'} . $obj . '.cu');
          $srcfiles->{'cu'}->{$cufile} = 1;
          if (!-e &{$osPathConversion}($cufile)) {
		    print "ERROR: file $cfile nor $cufile not found - project $projname\n";
		  }
        } else {
          if (!-e &{$osPathConversion}($cfile)) {
		    print "ERROR?: file $cfile not found - project $projname\n";
		  }
        }
      } else {
        $srcfiles->{'cc'}->{$cfile} = 1;
	  }
    }
  } else {
    $conftype = "Application";

    my $cfile = winPath($projlist->{ALL}->{$projname}->{'path'} . $projname . '.cc');
    $srcfiles->{'cc'}->{$cfile} = 1;
  }

  # add .h files + check that .cc files exist
  foreach my $cfile (keys %{$srcfiles->{'cc'}}) {
    if (!-e &{$osPathConversion}($cfile)) {
      print "ERROR: file $cfile not found - project $projname\n";
    }
    my $hfile = $cfile;
    $hfile =~ s/\.[^\.]+$/.h/;
    if (-e &{$osPathConversion}($hfile)) {
      $srcfiles->{'h'}->{$hfile} = 1;
    }
    my $hinlfile = $cfile;
    $hinlfile =~ s/\.[^\.]+$/-inl.h/;
    if (-e &{$osPathConversion}($hinlfile)) {
      $srcfiles->{'h'}->{$hinlfile} = 1;
    }
  }

  open(PROJ, '>', &{$osPathConversion}($projFileName));
  print PROJ
"<?xml version=\"1.0\" encoding=\"utf-8\"?>
<Project DefaultTargets=\"Build\" ToolsVersion=\"$TOOLS{$vsver}\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">
  <ItemGroup Label=\"ProjectConfigurations\">
    <ProjectConfiguration Include=\"Debug|Win32\">
      <Configuration>Debug</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include=\"Debug|x64\">
      <Configuration>Debug</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include=\"Release|Win32\">
      <Configuration>Release</Configuration>
      <Platform>Win32</Platform>
    </ProjectConfiguration>
    <ProjectConfiguration Include=\"Release|x64\">
      <Configuration>Release</Configuration>
      <Platform>x64</Platform>
    </ProjectConfiguration>
  </ItemGroup>
  <PropertyGroup Label=\"Globals\">
    <ProjectGuid>" . $guid . "</ProjectGuid>
    <Keyword>Win32Proj</Keyword>
    <RootNamespace>" . $rootnamespace . "</RootNamespace>
  </PropertyGroup>
";

  if ($projlist->{ALL}->{$projname}->{'type'} =~ /LIBNAME/) { # Microsoft.Cpp.Default.props - Library
    print PROJ
"  <Import Project=\"\$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />
  <PropertyGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|Win32'\" Label=\"Configuration\">
    <ConfigurationType>" . $conftype . "</ConfigurationType>
    <CharacterSet>Unicode</CharacterSet>
    <PlatformToolset>$TOOLSET{$vsver}</PlatformToolset>
  </PropertyGroup>
  <PropertyGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|x64'\" Label=\"Configuration\">
    <ConfigurationType>" . $conftype . "</ConfigurationType>
    <CharacterSet>Unicode</CharacterSet>
    <PlatformToolset>$TOOLSET{$vsver}</PlatformToolset>
  </PropertyGroup>
  <PropertyGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Release|Win32'\" Label=\"Configuration\">
    <ConfigurationType>" . $conftype . "</ConfigurationType>
    <CharacterSet>Unicode</CharacterSet>
    <PlatformToolset>$TOOLSET{$vsver}</PlatformToolset>
    <WholeProgramOptimization>true</WholeProgramOptimization>
  </PropertyGroup>
  <PropertyGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Release|x64'\" Label=\"Configuration\">
     <ConfigurationType>" . $conftype . "</ConfigurationType>
     <CharacterSet>Unicode</CharacterSet>
     <PlatformToolset>$TOOLSET{$vsver}</PlatformToolset>
     <WholeProgramOptimization>true</WholeProgramOptimization>
  </PropertyGroup>
";
  } else {  # Microsoft.Cpp.Default.props - Binfile
    print PROJ
"  <Import Project=\"\$(VCTargetsPath)\\Microsoft.Cpp.Default.props\" />
  <PropertyGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|Win32'\" Label=\"Configuration\">
    <ConfigurationType>" . $conftype . "</ConfigurationType>
    <UseDebugLibraries>true</UseDebugLibraries>
    <CharacterSet>Unicode</CharacterSet>
    <PlatformToolset>$TOOLSET{$vsver}</PlatformToolset>
  </PropertyGroup>
  <PropertyGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Release|Win32'\" Label=\"Configuration\">
    <ConfigurationType>" . $conftype . "</ConfigurationType>
    <UseDebugLibraries>false</UseDebugLibraries>
    <WholeProgramOptimization>true</WholeProgramOptimization>
    <CharacterSet>Unicode</CharacterSet>
    <PlatformToolset>$TOOLSET{$vsver}</PlatformToolset>
  </PropertyGroup>
  <PropertyGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|x64'\" Label=\"Configuration\">
    <ConfigurationType>" . $conftype . "</ConfigurationType>
    <UseDebugLibraries>true</UseDebugLibraries>
    <CharacterSet>Unicode</CharacterSet>
    <PlatformToolset>$TOOLSET{$vsver}</PlatformToolset>
  </PropertyGroup>
  <PropertyGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Release|x64'\" Label=\"Configuration\">
    <ConfigurationType>" . $conftype . "</ConfigurationType>
    <UseDebugLibraries>false</UseDebugLibraries>
    <WholeProgramOptimization>true</WholeProgramOptimization>
    <CharacterSet>Unicode</CharacterSet>
    <PlatformToolset>$TOOLSET{$vsver}</PlatformToolset>
  </PropertyGroup>
";
  }

  print PROJ
"  <Import Project=\"\$(VCTargetsPath)\\Microsoft.Cpp.props\" />
  <ImportGroup Label=\"ExtensionSettings\">
";
  if ($ENABLED{CUDA}) {
  print PROJ
'    <Import Project="$(VCTargetsPath)\BuildCustomizations\CUDA 7.0.props" />
'
  }
  print PROJ
"  </ImportGroup>
  <ImportGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|Win32'\"  Label=\"PropertySheets\">
    <Import Project=\"..\\variables.props\" />
    <Import Project=\"\$(UserRootDir)\\Microsoft.Cpp.\$(Platform).user.props\" Condition=\"exists('\$(UserRootDir)\\Microsoft.Cpp.\$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />
";
  if ($ENABLED{CUDA}) {
  print PROJ
"    <Import Project=\"..\\cuda_7.0.props\" />
"
  }
  print PROJ
"    <Import Project=\"..\\kaldiwin_win32.props\" />
    <Import Project=\"..\\openfstwin_debug_win32.props\" />
  </ImportGroup>
  <ImportGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|x64'\" Label=\"PropertySheets\">
    <Import Project=\"..\\variables.props\" />
    <Import Project=\"\$(UserRootDir)\\Microsoft.Cpp.\$(Platform).user.props\" Condition=\"exists('\$(UserRootDir)\\Microsoft.Cpp.\$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />
";
  if ($ENABLED{CUDA}) {
  print PROJ
"    <Import Project=\"..\\cuda_7.0.props\" />
";
  }
  print PROJ
"    <Import Project=\"..\\kaldiwin.props\" />
    <Import Project=\"..\\openfstwin_debug.props\" />
  </ImportGroup>
  <ImportGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Release|Win32'\" Label=\"PropertySheets\">
    <Import Project=\"..\\variables.props\" />
    <Import Project=\"\$(UserRootDir)\\Microsoft.Cpp.\$(Platform).user.props\" Condition=\"exists('\$(UserRootDir)\\Microsoft.Cpp.\$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />
";
  if ($ENABLED{CUDA}) {
  print PROJ
"    <Import Project=\"..\\cuda_7.0.props\" />
";
  }
  print PROJ
"    <Import Project=\"..\\kaldiwin_win32.props\" />
    <Import Project=\"..\\openfstwin_release_win32.props\" />
  </ImportGroup>
  <ImportGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Release|x64'\" Label=\"PropertySheets\">
    <Import Project=\"..\\variables.props\" />
    <Import Project=\"\$(UserRootDir)\\Microsoft.Cpp.\$(Platform).user.props\" Condition=\"exists('\$(UserRootDir)\\Microsoft.Cpp.\$(Platform).user.props')\" Label=\"LocalAppDataPlatform\" />
";
  if ($ENABLED{CUDA}) {
  print PROJ
"    <Import Project=\"..\\cuda_7.0.props\" />
";
  }
  print PROJ
"    <Import Project=\"..\\kaldiwin.props\" />
    <Import Project=\"..\\openfstwin_release.props\" />
  </ImportGroup>
";

  if ($projlist->{ALL}->{$projname}->{'type'} =~ /LIBNAME/) { # UserMacros - Library
    print PROJ
"  <PropertyGroup Label=\"UserMacros\" />
  <PropertyGroup>
    <_ProjectFileVersion>10.0.30319.1</_ProjectFileVersion>
    <OutDir Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|Win32'\">\$(SolutionDir)\$(Configuration)\\</OutDir>
    <IntDir Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|Win32'\">\$(Configuration)\\</IntDir>
    <OutDir Condition=\"'\$(Configuration)|\$(Platform)'=='Release|Win32'\">\$(SolutionDir)\$(Configuration)\\</OutDir>
    <IntDir Condition=\"'\$(Configuration)|\$(Platform)'=='Release|Win32'\">\$(Configuration)\\</IntDir>
  </PropertyGroup>
";
  } else {  # UserMacros - Binfile
    print PROJ
"  <PropertyGroup Label=\"UserMacros\" />
  <PropertyGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|Win32'\">
    <LinkIncremental>true</LinkIncremental>
  </PropertyGroup>
  <PropertyGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|x64'\">
    <LinkIncremental>true</LinkIncremental>
  </PropertyGroup>
  <PropertyGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Release|Win32'\">
    <LinkIncremental>false</LinkIncremental>
  </PropertyGroup>
  <PropertyGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Release|x64'\">
    <LinkIncremental>false</LinkIncremental>
  </PropertyGroup>
";
  }

  if ($projlist->{ALL}->{$projname}->{'type'} =~ /LIBNAME/) { # ItemDefinitionGroup Conditions - Library
    print PROJ
"  <ItemDefinitionGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|Win32'\">
    <ClCompile>
      <Optimization>Disabled</Optimization>
      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <MinimalRebuild>true</MinimalRebuild>
      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <WarningLevel>Level3</WarningLevel>
      <DebugInformationFormat>EditAndContinue</DebugInformationFormat>
    </ClCompile>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|x64'\">
    <ClCompile>
      <Optimization>Disabled</Optimization>
      <PreprocessorDefinitions>WIN32;_DEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <MinimalRebuild>true</MinimalRebuild>
      <BasicRuntimeChecks>EnableFastChecks</BasicRuntimeChecks>
      <RuntimeLibrary>MultiThreadedDebugDLL</RuntimeLibrary>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <WarningLevel>Level3</WarningLevel>
      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
    </ClCompile>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Release|Win32'\">
    <ClCompile>
      <Optimization>MaxSpeed</Optimization>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <WarningLevel>Level3</WarningLevel>
      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
    </ClCompile>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Release|x64'\">
    <ClCompile>
      <Optimization>MaxSpeed</Optimization>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <PreprocessorDefinitions>WIN32;NDEBUG;_LIB;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <WarningLevel>Level3</WarningLevel>
      <DebugInformationFormat>ProgramDatabase</DebugInformationFormat>
    </ClCompile>
  </ItemDefinitionGroup>
";
  } else {  # ItemDefinitionGroup Conditions - Binfile
    print PROJ
"  <ItemDefinitionGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|Win32'\">
    <ClCompile>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <WarningLevel>Level3</WarningLevel>
      <Optimization>Disabled</Optimization>
      <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
    </Link>
  </ItemDefinitionGroup>
   <ItemDefinitionGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Debug|x64'\">
     <ClCompile>
       <PrecompiledHeader>
       </PrecompiledHeader>
       <WarningLevel>Level3</WarningLevel>
       <Optimization>Disabled</Optimization>
       <PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
     </ClCompile>
     <Link>
       <SubSystem>Console</SubSystem>
       <GenerateDebugInformation>true</GenerateDebugInformation>
     </Link>
   </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Release|Win32'\">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <Optimization>MaxSpeed</Optimization>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
      <EnableCOMDATFolding>true</EnableCOMDATFolding>
      <OptimizeReferences>true</OptimizeReferences>
    </Link>
  </ItemDefinitionGroup>
  <ItemDefinitionGroup Condition=\"'\$(Configuration)|\$(Platform)'=='Release|x64'\">
    <ClCompile>
      <WarningLevel>Level3</WarningLevel>
      <PrecompiledHeader>
      </PrecompiledHeader>
      <Optimization>MaxSpeed</Optimization>
      <FunctionLevelLinking>true</FunctionLevelLinking>
      <IntrinsicFunctions>true</IntrinsicFunctions>
      <PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
    </ClCompile>
    <Link>
      <SubSystem>Console</SubSystem>
      <GenerateDebugInformation>true</GenerateDebugInformation>
      <EnableCOMDATFolding>true</EnableCOMDATFolding>
      <OptimizeReferences>true</OptimizeReferences>
    </Link>
  </ItemDefinitionGroup>
";
  }

  # .c files
  if (scalar keys %{$srcfiles->{'cc'}} > 0) {
    print PROJ
"  <ItemGroup>
";
    foreach my $cfile (sort { $a cmp $b } keys %{$srcfiles->{'cc'}}) {
      print PROJ
"    <ClCompile Include=\"" . makeRelPath($cfile, $projFileName) . "\" />
";
    }
    print PROJ
"  </ItemGroup>
";
  }
  # .cu files
  if (scalar keys %{$srcfiles->{'cu'}} > 0) {
    print PROJ
"  <ItemGroup>
";
    foreach my $cfile (sort { $a cmp $b } keys %{$srcfiles->{'cu'}}) {
      print PROJ
"    <CudaCompile Include=\"" . makeRelPath($cfile, $projFileName) . "\" />
";
    }
    print PROJ
"  </ItemGroup>
";
  }

  # .h files
  if (scalar keys %{$srcfiles->{'h'}} > 0) {
    print PROJ
"  <ItemGroup>
";
    foreach my $hfile (sort { $a cmp $b } keys %{$srcfiles->{'h'}}) {
      print PROJ
"    <ClInclude Include=\"" . makeRelPath($hfile, $projFileName) . "\" />
";
    }
    print PROJ
"  </ItemGroup>
";
  }

  # refs
  if (($projlist->{ALL}->{$projname}->{'type'} !~ /LIBNAME/) &&
      (scalar keys %{$projdeps->{$projlist->{ALL}->{$projname}->{'path'}}} > 0)) {
    print PROJ
"  <ItemGroup>
";
    foreach my $lib (sort { $a cmp $b } keys%{$projdeps->{$projlist->{ALL}->{$projname}->{'path'}}}) {
      my $refProjFileName = makeRelPath(winPath(getProjFileDir($lib) . "/$lib.vcxproj"), $projFileName);
      print PROJ
"    <ProjectReference Include=\"" . $refProjFileName . "\">
      <Project>" .   lc($projguids->{$lib}) . "</Project>
    </ProjectReference>
";
    }
    print PROJ
"  </ItemGroup>
";
  }

  # terminate
  print PROJ
"  <Import Project=\"\$(VCTargetsPath)\\Microsoft.Cpp.targets\" />
  <ImportGroup Label=\"ExtensionTargets\">
";
  if ($ENABLED{CUDA}) {
    print PROJ
'    <Import Project="$(VCTargetsPath)\BuildCustomizations\CUDA 7.0.targets" />
';
  }
  print PROJ
"  </ImportGroup>
</Project>
";
  close(PROJ);

  # create .user file
  #   my $filename_userfile = $projFileName . '.user';
    # open(USER, '>', &{$osPathConversion}($filename_userfile));
    # print USER
  # "<?xml version=\"1.0\" encoding=\"utf-8\"?>
  # <Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">
  # </Project>
  # ";
    # close(USER);

  # create .filters file
  my $filename_filtersfile = $projFileName . '.filters';
  open(FLTS, '>', &{$osPathConversion}($filename_filtersfile));
  print FLTS
"<?xml version=\"1.0\" encoding=\"utf-8\"?>
<Project ToolsVersion=\"4.0\" xmlns=\"http://schemas.microsoft.com/developer/msbuild/2003\">
  <ItemGroup>
    <Filter Include=\"Source Files\">
      <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
      <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
    </Filter>
    <Filter Include=\"Header Files\">
      <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
      <Extensions>h;hpp;hxx;hm;inl;inc;xsd</Extensions>
    </Filter>
    <Filter Include=\"Resource Files\">
      <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
      <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
    </Filter>
    <Filter Include=\"Cuda Kernels\">
      <UniqueIdentifier>{6841a02e-469b-487d-a1ea-7d138415dd41}</UniqueIdentifier>
      <Extensions>cu</Extensions>
    </Filter>
  </ItemGroup>
";
  # .c files
  if (scalar keys %{$srcfiles->{'cc'}} > 0) {
    print FLTS
"  <ItemGroup>
";
    foreach my $cfile (sort { $a cmp $b } keys %{$srcfiles->{'cc'}}) {
      print FLTS
"    <ClCompile Include=\"" . makeRelPath($cfile, $projFileName) . "\">
      <Filter>Source Files</Filter>
    </ClCompile>
";
    }
    print FLTS
"  </ItemGroup>
";
  }
  # .h files
  if (scalar keys %{$srcfiles->{'h'}} > 0) {
    print FLTS
"  <ItemGroup>
";
    foreach my $hfile (sort { $a cmp $b } keys %{$srcfiles->{'h'}}) {
      print FLTS
"    <ClInclude Include=\"" . makeRelPath($hfile, $projFileName) . "\">
      <Filter>Header Files</Filter>
    </ClInclude>
";
    }
    print FLTS
"  </ItemGroup>
";
  }
  # .cu files
  if (scalar keys %{$srcfiles->{'cu'}} > 0) {
    print FLTS
"  <ItemGroup>
";
    foreach my $cufile (sort { $a cmp $b } keys %{$srcfiles->{'cu'}}) {
      print FLTS
"    <CudaCompile Include=\"" . makeRelPath($cufile, $projFileName) . "\">
      <Filter>Cuda Kernels</Filter>
    </CudaCompile>
";
    }
    print FLTS
"  </ItemGroup>
";
  }
  print FLTS
"</Project>
";
  close(FLTS);
}


sub ltrim {
   my $s = shift;
    $s =~ s/^\s+//;
     return $s;
}

sub isEmptyLine{
   my $line = shift;

   my $lineTrimmed  = ltrim($line);

   if($lineTrimmed eq "")
   {
       return 1;
   }
   else
   {
       return 0;
   }
}

sub isValidProjectLine{
   my $line = shift;

   if(!( isEmptyLine($line) || $line =~ m:(EXT_SUBDIRS_LIB.*\n{0,1}): ) )
   {
       return 1;
   }
   else
   {
       return 0;
   }
}




# ****************************************************
# ****************************************************
# ****************************************************

if (-e &{$osPathConversion}($solutionDir)) {
  print "Solution directory already exists, do you want to (r)emove, (o)verwrite, or (c)ancel? : ";
  my $ans = <STDIN>;
  if ($ans =~ /^c$/i) { exit 0; }
  elsif($ans =~ /^r/i) { &{$osPathConversion}($solutionDir); }
  elsif($ans !~ /^o/) { die "Invalid option given."; }
}
mkpath &{$osPathConversion}($solutionDir);
mkpath &{$osPathConversion}($projDir);

my $projguids = {};
loadHashTxtFile($projguidListFileName, $projguids);

my $projlist = {};
my $projdeps = {};
my $projlibs = {};

#my $makefiles = [];
#find(sub { if ($_ =~ /Makefile$/) { push @$makefiles, $File::Find::name; } },
#     &{$osPathConversion}($srcDir));

my @makefiles = (); # will be all the Makefiles in the subdirectories.
my $topLevelMakefile = "$srcDir/Makefile";
open(M, '<', &{$osPathConversion}($topLevelMakefile)) || die "opening $topLevelMakefile";
while(<M>) {
  # parsing the part of the top-level Makefile that's like:
  # SUBDIRS = base util matrix feat tree model fstext hmm optimization \
  #	    transform lm decoder bin fstbin gmmbin featbin
  if (s/^(SUBDIRS|EXT_SUBDIRS)\s+=\s+//) {
    # print STDERR "here\n";
    while ( isValidProjectLine($_) ) { # till we get an empty line or a line starting with EXT_SUBDIRS_LIB..
      s:\\::;
      foreach my $f (split(" ", $_)) {
       if($f eq "#"){
           last;
       }
        push @makefiles, "$srcDir/$f/Makefile";
      }
      $_ = <M>;
    }
  }
}
##foreach my $f (@makefiles) { print STDERR "Adding $f\n"; }

# was @$makefiles in the line below.
my $i = 0;
foreach my $makefile (@makefiles) {
  print "INFO: parsing " . $makefile . "\n";
  parseMakefile($makefile, $projlist, $projdeps, $projlibs);
	#print Dumper("Projlist", $projlist);
	#print Dumper("Projdeps", $projdeps);
	#print Dumper("Projlibs", $projlibs);
	#die "To staci" if $i >=3;
	$i++;
  }

# writeSolutionFile also creates guids for new projects
writeSolutionFile($solutionDir . '/' . $solutionFileName, $projlist, $projguids);

foreach my $propFile (@propsFiles) {
  copy(&{$osPathConversion}($propFile),
       &{$osPathConversion}($projDir . "/")) or die "ERROR: failed to copy prop file $propFile\n";
}
foreach my $option (keys %optionalProps) {
	if ($ENABLED{$option} ) {
		my $propFile = $optionalProps{$option};
		copy(&{$osPathConversion}($propFile), &{$osPathConversion}($projDir . "/")) or
			die "ERROR: failed to copy prop file $propFile\n";
	}
}

foreach my $projname (sort { $a cmp $b } keys %{$projlist->{ALL}}) {
  my $projFileDir = winPath(getProjFileDir($projname));
  mkpath &{$osPathConversion}($projFileDir);
  writeProjectFiles($projname, $projlist, $projdeps, $projlibs, $projguids);
}

saveHashTxtFile($projguidListFileName, $projguids);

# make Windows line-endings in non-Win environment
if ($^O !~ /MSWin32/i) {
  my $allfiles = [];
  find(sub { if ($_ =~ /sln$|vcxproj$|props$/) { push @$allfiles, $File::Find::name; } },
       &{$osPathConversion}($solutionDir));
  foreach my $file (@$allfiles) {
    checkCRLF($file);
  }
}