Import-Module PSWriteColor

#Define important variables and information
$Locations = @(
	'F:\Library\Graphic Novels\Comic'
	'F:\Library\Graphic Novels\Manga'
	'F:\Library\Graphic Novels\WebToon'
	'F:\Library\Graphic Novels\Comic\Block 109'
	'F:\Library\Graphic Novels\Comic\Sabrina'
	'F:\Library\Graphic Novels\Comic\Doggybags'
	'F:\Library\Graphic Novels\Comic\Alien'
	'F:\Library\Graphic Novels\Comic\Hawkman'
	'F:\Library\Graphic Novels\Comic\Outer Darkness'
	'F:\Library\Graphic Novels\Comic\Secret Wars'
	'F:\Library\Graphic Novels\Comic\Teenage Mutant Ninja Turtles'
	'F:\Library\Graphic Novels\Comic\Hulk'
	'F:\Library\Graphic Novels\Comic\Wonder Woman'
	"F:\Library\Graphic Novels\Comic\Conan The Barbarian"
	"F:\Library\Graphic Novels\Comic\Avengers"
	"F:\Library\Graphic Novels\Comic\Amory Wars"
	"F:\Library\Graphic Novels\Comic\Batman"
	"F:\Library\Graphic Novels\Comic\Borderlands"
	"F:\Library\Graphic Novels\Comic\Brit"
	"F:\Library\Graphic Novels\Comic\Clive Barker"
	"F:\Library\Graphic Novels\Comic\Colder"
	"F:\Library\Graphic Novels\Comic\Constantine"
	"F:\Library\Graphic Novels\Comic\Critical Role"
	"F:\Library\Graphic Novels\Comic\Dark Ark"
	"F:\Library\Graphic Novels\Comic\Deadpool"
	"F:\Library\Graphic Novels\Comic\Dicks"
	"F:\Library\Graphic Novels\Comic\Ether"
	"F:\Library\Graphic Novels\Comic\Fables"
	"F:\Library\Graphic Novels\Comic\Grimm Fairy Tales"
	"F:\Library\Graphic Novels\Comic\Guardians of the Galaxy"
	"F:\Library\Graphic Novels\Comic\Gwenpool"
	"F:\Library\Graphic Novels\Comic\Hack Slash"
	"F:\Library\Graphic Novels\Comic\Harley Quinn"
	"F:\Library\Graphic Novels\Comic\Hellboy"
	"F:\Library\Graphic Novels\Comic\Hercules"
	"F:\Library\Graphic Novels\Comic\Joker"
	"F:\Library\Graphic Novels\Comic\Justice League"
	"F:\Library\Graphic Novels\Comic\Kick-Ass"
	"F:\Library\Graphic Novels\Comic\Lazarus"
	"F:\Library\Graphic Novels\Comic\Lobo"
	"F:\Library\Graphic Novels\Comic\Mad Max"
	"F:\Library\Graphic Novels\Comic\Teen Titans"
	"F:\Library\Graphic Novels\Comic\Midnighter"
	"F:\Library\Graphic Novels\Comic\Nailbiter"
	"F:\Library\Graphic Novels\Comic\Pilot Season"
	"F:\Library\Graphic Novels\Comic\Punisher"
	"F:\Library\Graphic Novels\Comic\Predator"
	"F:\Library\Graphic Novels\Comic\Rumble"
	"F:\Library\Graphic Novels\Comic\Sonic"
	"F:\Library\Graphic Novels\Comic\Star Wars"
	"F:\Library\Graphic Novels\Comic\Suicide Squad"
	"F:\Library\Graphic Novels\Comic\Spider-Man"
	"F:\Library\Graphic Novels\Comic\The Boys"
	"F:\Library\Graphic Novels\Comic\The Last Zombie"
	"F:\Library\Graphic Novels\Comic\The Realm"
	"F:\Library\Graphic Novels\Comic\The Walking Dead"
	"F:\Library\Graphic Novels\Comic\Thor"
	"F:\Library\Graphic Novels\Comic\Transformers"
	"F:\Library\Graphic Novels\Comic\Venom"
	"F:\Library\Graphic Novels\Comic\Vikings"
	"F:\Library\Graphic Novels\Comic\WWE"
	"F:\Library\Graphic Novels\Comic\X-Men"
	"F:\Library\Graphic Novels\Comic\X-Men\Wolverine"
	"F:\Library\Graphic Novels\Comic\X-Men\X-Men"
	"F:\Library\Graphic Novels\Manga\GUNNM"
	"F:\Library\Graphic Novels\Manga\Battle Through The Heavens"
	"F:\Library\Graphic Novels\Manga\Boku No Hero Academia"
	"F:\Library\Graphic Novels\Manga\Dr. Stone"
	"F:\Library\Graphic Novels\Manga\Franken Fran"
	"F:\Library\Graphic Novels\Manga\Kakegurui"
	"F:\Library\Graphic Novels\Manga\Kami-Sama No Iutoori"
	"F:\Library\Graphic Novels\Manga\Shaman King"
	"F:\Library\Graphic Novels\Manga\Tensei Shitara Slime Datta Ken"
	"F:\Library\Graphic Novels\Manga\Touhou"
	"F:\Library\Graphic Novels\Manga\Touhou\Official"
	"F:\Library\Graphic Novels\Manga\Touhou\Doujinshi"
	)
$rootDirectory = 'F:\Library\Graphic Novels'
[string[]]$blackList = @("*Director's cut*",'*16777215*', '*Occult Edition*', '*Preview*', '*All Out War Artist Proof Edition*','*Script*','*I Hate It Here*','*Filth of the City*', 'folder*', '*TPB*', '*annual*', '*special*', '*full*', '*primer*', '*Colección*', '*book*', '*1000000*', '*extra*')
[string[]]$whiteList = @('Wolverine (2003)','Borderlands ~ Tannis & the Vault', 'Star Wars ~ Republic','Star Wars ~ Rebels Magazine','*Akira*','Gyo','Uncanny X-Men (2013)','Franken Fran', 'GUNNM', 'The Transformers (2014)', 'The Transformers ~ Regeneration One', 'Transformers ~ Energon', 'Dark Wolverine', 'Wolverine (2010)', 'All-New Guardians of the Galaxy', 'Incredible Hercules', 'Mighty Thor (2016)', 'Venom (2016)', 'Dorohedoro', 'Montage (WATANABE Jun)')
$pattern = '((\d+)(\.\d)?)((?=\.cbz)|(?=\.zip))' #Pattern of the numbers
[regex]$rx = $pattern

#Functions downloaded from the internet
function SortNaturally{
    PARAM(
        [string[]]$strArray
    )

    Add-Type -TypeDefinition @'
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;

namespace NaturalSort {
    public static class NaturalSort
    {
        [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)]
        public static extern int StrCmpLogicalW(string psz1, string psz2);

        public static System.Collections.ArrayList Sort(System.Collections.ArrayList foo)
        {
            foo.Sort(new NaturalStringComparer());
            return foo;
        }
    }

    public class NaturalStringComparer : IComparer
    {
        public int Compare(object x, object y)
        {
            return NaturalSort.StrCmpLogicalW(x.ToString(), y.ToString());
        }
    }
}
'@

    return [NaturalSort.NaturalSort]::Sort($strArray)
}

function deleteDuplicates {
    param(
    [Parameter(
    Mandatory=$True,
    ValueFromPipeline=$True,
    ValueFromPipelineByPropertyName=$True
    )]
    [string[]]$PathDuplicates)

    $DuplicatePaths = 
        Get-ChildItem $PathDuplicates -Recurse| 
        Get-FileHash |
        Group-Object -Property Hash |
        Where-Object -Property Count -gt 1 |
        ForEach-Object {
            $_.Group.Path |
            Select-Object -First ($_.Count -1)}
    $TotalCount = (Get-ChildItem $PathDuplicates).Count
    Write-Warning ("You are going to delete {0} files out of {1} total. Please confirm the prompt" -f $DuplicatePaths.Count, $TotalCount)
	Invoke-Item $DuplicatePaths
    $DuplicatePaths | Remove-Item -Confirm
}

#My own functions

function Write-Separator{Write-Color '---' -Color DarkGray}
function checkDecimals($name, $indexNumber, $testFile){
	$testFileDecimal = @(
		$name + ' - ' + $indexNumber + '.' + 0 + '.cbz'
		$name + ' - ' + $indexNumber + '.' + 1 + '.cbz'
		$name + ' - ' + $indexNumber + '.' + 2 + '.cbz'
		$name + ' - ' + $indexNumber + '.' + 3 + '.cbz'
		$name + ' - ' + $indexNumber + '.' + 4 + '.cbz'
		$name + ' - ' + $indexNumber + '.' + 5 + '.cbz'
		$name + ' - ' + $indexNumber + '.' + 6 + '.cbz'
		$name + ' - ' + $indexNumber + '.' + 7 + '.cbz'
		$name + ' - ' + $indexNumber + '.' + 8 + '.cbz'
		$name + ' - ' + $indexNumber + '.' + 9 + '.cbz'
	)
	$openDir = $true
	for ($i = 0; $i -lt $testFileDecimal.Count; $i++)
	{
		if (Test-Path($testFileDecimal[$i])){
			$openDir = $false
		}
	}
	if ($openDir -eq $true){
		$dir = Get-Location
		Write-Color 'The issue ', $testFile, ' is missing from the directory ', $dir -Color White, DarkRed, White, Red
	}
}
function removeEmptyDirectory{
	remove-emtpy.ps1 -Path .\ -Remove -VerifyNoEmpty
}

function decompress{
	foreach ($file in Get-ChildItem *.cbz -Recurse) { #Creates a list of CBZ files on all the subdirectories and runs for each one
		Clear-Host #This will make the screen flash so it becomes somewhat readable. 
		Set-Location $file.DirectoryName #Changes location to a children directory to avoid uncompressing into the wrong folders
		7z x $file -o* 
		Remove-Item $file.FullName #Removes the CBZ file after extracted 
	}
}

function fixZip{
	foreach ($file in Get-ChildItem *.cbz -Recurse) { #Creates a list of CBZ files on all the subdirectories and runs for each one
		Clear-Host #This will make the screen flash so it becomes somewhat readable. 
		Set-Location $file.DirectoryName #Changes location to a children directory to avoid uncompressing into the wrong folders
		7z x $file -o* 
		$dirCreated = [io.path]::GetFileNameWithoutExtension($file)
		if (Test-Path -Path $dirCreated){
			#Get-ChildItem -Recurse ComicInfo.xml | Remove-Item
			Remove-Item $file.FullName #Removes the CBZ file after extracted 
			7z a "$dirCreated.zip" .\$dirCreated\*
			Remove-Item $dirCreated -Force -Recurse
		}
	}
}

function compress{ #Compress every comic folder that contains valid filetypes
	Set-Location $rootDirectory #Goes to the root in case anything changed
	foreach ($directory in Get-ChildItem -recurse -Directory){ 
		Set-Location $directory.FullName
		if ((Test-Path .\*.jpg -Exclude 'folder.jpg') -or (Test-Path .\*.png -Exclude 'folder.png') -or (Test-Path .\*.jpeg -Exclude 'folder.jpeg')){ #checks if the file contains valid images otherwise skips 
			Set-Location $directory.Parent.FullName
			$fileArray = Get-ChildItem $directory.FullName
			#foreach ($file in Get-ChildItem $directory.FullName){#Compress the folder with all the files found inside
			$chunkSize = 100
			$outFileArray = @()
			$parts =[math]::Ceiling($fileArray.Count / $chunkSize)
			if($fileArray.Count -eq 1){
				#$fileArray.FullName
				#$directory
				7z a "$directory.zip" $fileArray.FullName
				Remove-Item $fileArray.FullName -Force 
				if ((Get-ChildItem $directory).Count -eq 0){
					Remove-Item $directory
				}
			}
			elseif($fileArray.Count -gt 1){
				for($i=0; $i -lt $parts; $i++){
					$start = $i*$chunkSize
					$end = (($i+1)*$chunkSize)-1
					$outFileArray += ,@($fileArray[$start..$end])
					#Clear-Host #FLashes the screen so its possible to read 
					#7z a "$directory.zip" $file.FullName
					#Remove-Item $file.FullName -Force 
				}
				for ($i=0; $i -lt $outFileArray.Count; $i++){
					#$outFileArray[$i]
					7z a "$directory.zip" $outFileArray[$i].FullName
					Remove-Item $outFileArray[$i].FullName -Force 
				}
				if ((Get-ChildItem $directory).Count -eq 0){
					Remove-Item $directory
				}
			}
		}
	}
    Set-Location $rootDirectory #As the progam exits the loop go back to the root directory
}

function cleanNames{
	$allDirs = Get-ChildItem -Directory
	$allFiles = Get-ChildItem -Recurse -File -Depth 1

	#Rename files with year on the name so the scrapper can identify them better
	$patternConflict = @(
		'\((\d{4})\) '
		'(?<!\()((\d{4} )(?!\))(?!\.\d)(?!.zip))'
	)
	$list = Get-ChildItem -Recurse -File -Exclude $blackList
	foreach ($patternMatch in $patternConflict){
		$newList = $list | Where-Object {$_.Name -match $patternMatch} #Creates a list of all the matching conflicting names
		foreach ($file in $newList){
			Set-Location $file.DirectoryName
			$newName = $file.Name -replace ($patternMatch,'')
			Write-Separator
			Write-Color 'File directory: ', $file.DirectoryName -Color White, Green
			Write-Color $file.Name, ' will be renamed into ', $newName -Color  Red, White, Green
			Rename-Item -Path $file -NewName .\$newName
		}
		$newList = @() #Clean the previous list to avoid problems
	}

	$nameConflict = @(
		'_ '
		' _'
		'  '
		" 's"
		'Konjiki No Moji Tsukai - Yuusha Yonin Ni Makikomareta Unique Cheat'
		'Onepunch Man'
		'Justice League Dark'
		'Tensei Shitara Slime Datta Ken ~ Mabutsu No Kuni No Arukikata'
		'Scoob-And-Shag'
		'Tower-Of-God'
		'The-God-Of-High-School'
		'Pixie-And-Brutus'
		'Stick-N-Poke'
		'Shaman King 0'
		'Shaman King Flowers'
		'Shaman King Man Ji En'
		'Shaman King Remix Track'
		'Shaman King The Super Star'
		'Kakegurui Midari'
		'Dragon Ball Chou'
		'Boruto Naruto Next Generations'
		'Vigilante Boku No Hero Academia Illegals'
		'Justice League Dark'
		'Outer Darkness_Chew'
		'Chi No Wadachi'
		'Tensei Shitara Slime Datta Ken ~ Mabutsu No Kuni No Arukikata'
		'X Men'
		'Gunnm Mars Chronicle'
		'Tensura Nikki Tensei Shitara Slime Datta Ken'
		"The Shinigami's Rowing Her Boat As Usual ~ Touhou"
		'Wonder Woman Dead Earth'
		'The Transformers Classics UK'
		'Harley Quinn Black + White + Red'
		'Yakusoku No Neverland'
		'Oyaji Ga Bishoujo Ni Natteta Hanashi'
		'Tensei Shitara Slime Datta Ken ~ Ibun Makuni Kurashi No Trinity'
	)
	$nameFix = @(
		' ~ '
		' '
		' '
		"'s"
		'Konjiki No Moji Tsukai ~ Yuusha Yonin Ni Makikomareta Unique Cheat'
		'Onepunch-Man'
		'Justice League ~ Dark'
		'Tensei Shitara Slime Datta Ken ~ The Ways Of Strolling In The Demon Country'
		'Scoob And Shag'
		'Tower Of God'
		'The God Of High School'
		'Pixie And Brutus'
		'Stick N Poke'
		'Shaman King ~ 0'
		'Shaman King ~ Flowers'
		'Shaman King ~ Man Ji En'
		'Shaman King ~ Remix Track'
		'Shaman King ~ The Super Star'
		'Kakegurui ~ Midari'
		'Dragon Ball Super'
		'Boruto ~ Naruto Next Generations'
		'Vigilante ~ Boku No Hero Academia Illegals'
		'Justice League ~ Dark'
		'Outer Darkness ~ Chew'
		'A Trail Of Blood'
		'Tensei Shitara Slime Datta Ken ~ The Ways Of Strolling In The Demon Country'
		'X-Men'
		'GUNNM ~ Mars Chronicle'
		'Tensura Nikki ~ Tensei Shitara Slime Datta Ken'
		"Touhou ~ The Shinigami's Rowing Her Boat As Usual"
		'Wonder Woman ~ Dead Earth'
		'The Transformers ~ Classics UK'
		'Harley Quinn ~ Black + White + Red'
		'The Promised Neverland'
		'My Father Became A Cute Vtuber Girl!'
		'Tensei Shitara Slime Datta Ken Ibun ~ Makuni Kurashi No Trinity'
	)

	#Fix filename number mismatch from different sources
	$theGreatRulerFiles = $allFiles | Where-Object {$_.Name -match 'The Great Ruler'} | Where-Object {$_.Name -match 'zip'}
	foreach ($file in $theGreatRulerFiles){
		[int]$TGRnumber = $rx.match($file).value
		if($TGRnumber -gt 340){
			$TGRNewNumber = $TGRnumber - 204
			$newName = $file.Name -replace ($TGRnumber, $TGRNewNumber)
			Write-Color $file.Name, ' will be renamed into ', $newName -Color  Red, White, Green
			Rename-Item $file -NewName $newName {[System.IO.Path]::ChangeExtension($_.Name, "cbz")}
		}
	} 
	$HarleyQuinRedBlackWhite = $allFiles | Where-Object {$_.Name -match "Harley Quinn Black \+ White \+ Red"}
	foreach ($file in $HarleyQuinRedBlackWhite){
		Write-Color $file.Name, ' will be renamed into ', $file.Name.Replace("Harley Quinn Black + White + Red", "Harley Quinn ~ Black + White + Red") -Color  Red, White, Green
		Rename-Item $file -NewName $file.Name.Replace("Harley Quinn Black + White + Red", "Harley Quinn ~ Black + White + Red")
	} 

	<#$apotheosisFiles = $allFiles | Where-Object {$_.Name -match 'Apotheosis'} | Where-Object {$_.Name -match 'zip'}
	foreach ($file in $apotheosisFiles){
		[int]$TGRnumber = $rx.match($file).value
		if($TGRnumber -gt 578){
			$TGRNewNumber = $TGRnumber + 3
			$newName = $file.Name -replace ($TGRnumber, $TGRNewNumber)
			Write-Color $file.Name, ' will be renamed into ', $newName -Color  Red, White, Green
			Rename-Item $file -NewName $newName 
		}
	}#>

	#Rename directories
	for ($i = 0; $i -lt $nameConflict.Count; $i++){
		#$nameFilter = '*' + $nameConflict[$i] + '*'
		$filteredDirs = $allDirs | Where-Object {$_.Name -imatch $nameConflict[$i]}
		$filteredFiles = $allFiles | Where-Object {$_.Name -imatch $nameConflict[$i]}
		foreach ($conflictName in $filteredFiles){
			if ($conflictName.Name.ToLower() -eq $conflictName.Name.Replace($nameConflict[$i], $nameFix[$i]).ToLower()){}
			else{
				Write-Color $conflictName.Name, " will be renamed into ", $conflictName.Name.Replace($nameConflict[$i], $nameFix[$i]) -Color Red, White, Green
				Rename-Item $conflictName.FullName -NewName $conflictName.Name.Replace($nameConflict[$i], $nameFix[$i])
			}
		}
		foreach ($conflictName in $filteredDirs){
			$newDir = $conflictName.Name.Replace($nameConflict[$i], $nameFix[$i])
			if(Test-Path ($newDir)){
				foreach ($file in Get-ChildItem -Path $conflictName){Move-Item $file -Destination $newDir}
			}
			elseif(!(Test-Path ($newDir))){
				Write-Separator
				Write-Color 'Will rename the directory ', $conflictName.Name, ' into ', $newDir -Color White, Red, White, Green
				Rename-Item $conflictName -NewName $newDir
			}
		}
	}
}

function folderCover{
	Set-Location $rootDirectory 
	$folderCoverArray = Get-ChildItem -Recurse -File 'folder*'
	<#foreach ($folderCover in $folderCoverArray){
		Set-Location $folderCover.Directory
		$directoryFiles = Get-ChildItem -Exclude $blackList
		$firstFile = SortNaturally -strArray $directoryFiles | Select-Object -First 1
		$firstFileDirectory = $firstFile.Split('.')
		7z x $firstFile -o* 
		Remove-Item $firstFile
		Move-Item $folderCover -Destination $firstFileDirectory[0]
	}#>
	$folderCoverArray
	Set-Location $rootDirectory 
	<#$folderCoverArray = Get-ChildItem -Recurse -File '0'
	$folderCoverArray
	foreach ($file in $folderCoverArray){Rename-Item $file -NewName '0.jpg'}
	$folderCoverArray = Get-ChildItem -Recurse -File '0.jpg'
	foreach ($file in $folderCoverArray){
		#magick mogrify -format png $file
		Remove-Item $file
	}#>
}


function pad{ #Pad filenames based on the newest number
	foreach ($directory in Get-ChildItem -recurse -Directory){ #Get directories
		Set-Location $directory #Changes to each child directory
		if ((Get-ChildItem | Measure-Object).Count -gt 0){ #If there are more than one files
			$directoryFiles = Get-ChildItem -Exclude $blackList
			if ($directoryFiles.Name -match $pattern){ #Loops trough all the files that contain a matching name
				#$lastFile = SortNaturally -strArray $directoryFiles | Select-Object -last 1 #Get the last file
				#Extract the number part of the name
				#[int]$number = $rx.match($lastFile).value
				foreach ($file in $directoryFiles){
					$paddedDigits = "{0:D4}" -f [int]($file.Name | Select-String -Pattern $pattern).matches.Groups[2].Value #calculate new name
					$newName = $file.Name -replace ($pattern, $($paddedDigits+'$3')) #replace new name
					if ($newName -ne $file.Name){
						Write-Color $file.Name, ' will be renamed into ', $newName -Color  Red, White, Green
						Rename-Item $file -NewName $newName #rename file
					}
				}
				<#if (($number -le 9999) -and ($number -ge 900)){#If file is part of a long series
					foreach ($file in $directoryFiles) 
					{
						$paddedDigits = "{0:D4}" -f [int]($file.Name | Select-String -Pattern $pattern).matches.Groups[2].Value #calculate new name
						$newName = $file.Name -replace ($pattern, $($paddedDigits+'$3')) #replace new name
						if ($newName -ne $file.Name){
							Write-Color $file.Name, ' will be renamed into ', $newName -Color  Red, White, Green
							Rename-Item $file -NewName $newName #rename file
						}
					}
				}
				if (($number -le 899) -and ($number -ge 70)){#If file is part of a long series
					foreach ($file in $directoryFiles) 
					{
						$paddedDigits = "{0:D3}" -f [int]($file.Name | Select-String -Pattern $pattern).matches.Groups[2].Value #calculate new name
						$newName = $file.Name -replace ($pattern, $($paddedDigits+'$3')) #replace new name
						if ($newName -ne $file.Name){
							Write-Color $file.Name, ' will be renamed into ', $newName -Color  Red, White, Green
							Rename-Item $file -NewName $newName #rename file
						}
					}
				}
				elseif (($number -le 99) -and ($number -ge 10)){#If file is part of a short series
					foreach ($file in $directoryFiles) 
					{
						$paddedDigits = "{0:D2}" -f [int]($file.Name | Select-String -Pattern $pattern).matches.Groups[2].Value #calculate new name
						$newName = $file.Name -replace ($pattern, $($paddedDigits+'$3')) #replace new name
						if ($newName -ne $file.Name){
							Write-Color $file.Name, ' will be renamed into ', $newName -Color  Red, White, Green
							Rename-Item $file -NewName $newName #rename file
						}
					}
				}
				elseif (($number -le 9)){#If file is part of a short series
					foreach ($file in $directoryFiles) 
					{
						$paddedDigits = "{0:D1}" -f [int]($file.Name | Select-String -Pattern $pattern).matches.Groups[2].Value #calculate new name
						$newName = $file.Name -replace ($pattern, $($paddedDigits+'$3')) #replace new name
						if ($newName -ne $file.Name){
							Write-Color $file.Name, ' will be renamed into ', $newName -Color  Red, White, Green
							Rename-Item $file -NewName $newName #rename file
						}
					}
				}#>
			}
		}
	}
}

function decimals{
	foreach ($directory in Get-ChildItem -Recurse -Directory -Exclude 'Akira'){
		Set-Location $directory
		$files = Get-ChildItem -File -Recurse -Exclude $blackList
		if ($files.Name -match '(\.\d)(?=\.cbz)'){
			foreach ($file in $files -match '(\.\d)(?=\.cbz)'){
				#$file.FullName
				$splitName = $file.Name.Split('.')
				$origName = $splitName[0] + '.cbz'
				if(Test-Path $origName){
					$newName = $splitName[0] + '.0.cbz'
					Write-Color $origName, ' will be renamed into ', $newName -Color Red, White, Green
					Rename-Item $origName -NewName $newName
				}
			}
		}
	}
}

function missingFiles{
	foreach ($directory in Get-ChildItem -Directory -Exclude $whiteList){
		Set-Location $directory
		$directoryFiles = Get-ChildItem -Exclude $blackList
		if ($directoryFiles.Name -match $pattern){
			[string]$lastFile = SortNaturally -strArray $directoryFiles.Name | Select-Object -last 1
			$number = $rx.match($lastFile).value
			$number = $number - 1
			#'((\d+)(\.\d)?)((?=\.cbz)|(?=\.zip))'
			#$name = $lastFile.Split(' - ') #Split the name of the file structure
			$name = [regex]::Split($lastFile, ' - \d+') #Split the name of the file structure
			[int]$number = $number
			for ($i=1; $i -le $number; $i++){
				$indexNumber = "{0:0000}" -f $i
				$testFile = $name[0] + ' - ' + $indexNumber + '.cbz'
				if(!(Test-Path ($testFile))){
					checkDecimals $name[0] $indexNumber $testFile
				}
			}

			<#for ($i=1; $i -le $number; $i++){	
				if (($number -le 9999) -and ($number -ge 900)){
					$indexNumber = "{0:0000}" -f $i
					$testFile = $name[0] + ' - ' + $indexNumber + '.cbz'
					if(!(Test-Path ($testFile))){
						checkDecimals $name[0] $indexNumber $testFile
					}
				}			
				if (($number -le 899) -and ($number -ge 70)){
					$indexNumber = "{0:000}" -f $i
					$testFile = $name[0] + ' - ' + $indexNumber + '.cbz'
					if(!(Test-Path ($testFile))){
						checkDecimals $name[0] $indexNumber $testFile
					}
				}
				elseif (($number -le 99) -and ($number -ge 10)){
					$indexNumber = "{0:00}" -f $i
					$testFile = $name[0] + ' - ' + $indexNumber + '.cbz'
					if(!(Test-Path ($testFile))){
						checkDecimals $name[0] $indexNumber $testFile
					}
				}
				elseif (($number -le 9)){
					$indexNumber = "{0:0}" -f $i
					$testFile = $name[0] + ' - ' + $indexNumber + '.cbz'
					if(!(Test-Path ($testFile))){
						checkDecimals $name[0] $indexNumber $testFile
					}
				}
				elseif ($number -eq 100){
					$testFile = $name[0] + ' - ' + 100 + '.cbz'
					if(!(Test-Path ($testFile))){
						$testFile
						$openDir = $true
					}
				}
			}#>
			if($openDir)
			{
				Invoke-Item .
				Read-Host -Prompt "Continue"
			}
		}
	}
}

function partZip {
	
	$partListDirectory = Get-ChildItem -Recurse -File *part*
	$partListDirectory = $partListDirectory.Directory | Sort-Object | Select-Object -Unique
	foreach ($partDirectory in $partListDirectory){
		$partListFile = @()
		Set-Location $partDirectory
		foreach ($partFile in Get-ChildItem -File *part*){
			$partListFileTemp = $partFile.Name.Split(" (Part")
			$partListFile += $partListFileTemp[0]
		}
		$partListFile = $partListFile | Sort-Object | Select-Object -Unique
		mkdir $partListFile
		<#foreach ($partListFileFile in $partListFile){
			foreach ($file in Get-ChildItem){
				$partListFileFile
				$file.NameString
				$file.NameString.Contains("$partListFile")
			}
		}#>
	}
}

function Move-Directories{
	$moveLocations =@(
		"F:\Library\Graphic Novels\Comic\"
		"F:\Library\Graphic Novels\Manga\"
	)
	foreach ($moveLocation in $moveLocations)	{
		Set-Location $moveLocation
		$dirCollection = @(
			'WWE'
			'Venom'
			'Transformers'
			'The Last Zombie'
			'The Boys'
			'Star Wars'
			'Pilot Season'
			'Midnighter'
			'Lobo'
			'Hellboy'
			'Fables'
			'Colder'
			'Clive Barker'
			'Brit'
			'Amory Wars'
			'Guardians of the Galaxy'
			'Klaus'
			'Batman'
			'Critical Role'
			'Hack Slash'
			'Justice League'
			'Nailbiter'
			'Lazarus'
			'Dark Ark'
			'Dicks'
			'Ether'
			'Grimm Fairy Tales'
			'Hercules'
			'Thor'
			'Punisher'
			'Rumble'
			'Sonic'
			'The Realm'
			'Vikings'
			'Mad Max'
			'Harley Quinn'
			'Joker'
			'Suicide Squad'
			'Deadpool'
			'Gwenpool'
			'Borderlands'
			'Battle Through The Heavens'
			'Boku No Hero Academia'
			'Franken Fran'
			'Kakegurui'
			'Shaman King'
			'GUNNM'
			'Touhou'
			"Teen Titans"
			'Avengers'
			'Block 109'
			'Sabrina'
			'Doggybags'
			'Hawkman'
			'Outer Darkness'
			'Secret Wars'
			'Teenage Mutant Ninja Turtles'
			'Hulk'
			'Wonder Woman'
			'Predator'
		)
		$dirCollectionBlacklist = @(
			'Kid Lobotomy'
			'War Of The Realms ~ Omega'
			'Teether'
			'Detective Conan'
		)
		$xmenCollection = @(
			'Wolverine'
			'Logan'
			'Sabretooth'
			'X-Men'
			'X-Force'
		)
		$kickassCollection = @(
			'Hit-Girl'
			'Kick-Ass'
		)
		$constantineCollection = @(
			'Constantine'
			'Hellblazer'
		)
		$spiderCollection = @(
			'Spider'
		)
		$slimeCollection = @(
			'Shitara Slime Datta Ken'
			'Tenchura! Tensei Shitara Slime Datta Ken'
		)
		$conanCollection = @(
			'Conan'
			'Cimmerian'
		)
		$alienCollection =@(
			'Alien'
			'Prometheus'
		)

		$collections = $conanCollection, $xmenCollection, $kickassCollection, $constantineCollection, $spiderCollection, $slimeCollection, $alienCollection
		$collectionsDirs = @(
			'Conan The Barbarian'
			'X-Men'
			'Kick-Ass'
			'Constantine'
			'Spider-Man'
			'Tensei Shitara Slime Datta Ken'
			'Alien'
		)
		#Collections
		$Directories = Get-ChildItem -Directory -Exclude $dirCollectionBlacklist
		for ($i = 0; $i -lt $dirCollection.Count; $i++){
			$matchingDirectories = $Directories | Where-Object {$_.Name -match $dirCollection[$i]}
			ForEach ($missplacedDirectory in $matchingDirectories){
				if ($missplacedDirectory.Name -ne $dirCollection[$i]){
					$destinationDir = $dirCollection[$i] + '\' + $missplacedDirectory.Name
					if(Test-Path $destinationDir){
						$dir2move = Get-ChildItem -Path $missplacedDirectory
						Write-Color 'Will move ', $dir2move, ' into ', $destinationDir -Color White, yellow, White, Green
						Move-Item $dir2move -Destination $destinationDir
					}
					else{
						Write-Color 'Will move ', $missplacedDirectory.Name, ' into ', $dirCollection[$i] -Color White, yellow, White, Green
						if(!(Test-Path $dirCollection[$i])){mkdir $dirCollection[$i]}
						Move-Item $missplacedDirectory -Destination $dirCollection[$i]
					}
				}
			}
		}
		#Special collections
		for ($i = 0; $i -lt $collections.Count; $i++){
			for ($ii = 0; $ii -lt $collections[$i].Count; $ii++){
				$currentCollection = $collections[$i][$ii]
				$matchingDirectories = $Directories | Where-Object {$_.Name -match $currentCollection}
				ForEach ($missplacedDirectory in $matchingDirectories){
					if ($missplacedDirectory.Name -ne $collectionsDirs[$i]){
						if(!(Test-Path $collectionsDirs[$i])){mkdir $collectionsDirs[$i]}
						Write-Color 'Will move ', $missplacedDirectory.Name, ' into ', $collectionsDirs[$i] -Color White, yellow, White, Green
						Move-Item $missplacedDirectory -Destination $collectionsDirs[$i]
					}
				}
			}
		}
	}
	
	#X-men folder
	Set-Location 'F:\Library\Graphic Novels\Comic\X-men'
	$Dirs = Get-ChildItem -Directory
	$wolvDirs = $Dirs | Where-Object {($_.Name -Match 'Wolverine' -or $_.Name -Match 'Sabretooth' -or $_.Name -Match 'Logan')}
	$xmenDirs = $Dirs | Where-Object {($_.Name -Match 'X-Men' -or $_.Name -Match 'X-Force')}
	$xCollections = $wolvDirs, $xmenDirs
	$xDirs = @(
		'Wolverine'
		'X-Men'
	)
	For ($i = 0; $i -lt $xCollections.Count; $i++){

		ForEach ($dir in $xCollections[$i]){
			if ($dir.Name -ne $xDirs[$i]){
				if (!(Test-Path $xDirs[$i])){mkdir $xDirs[$i]}
				$destinationDir = $xDirs[$i] + '\' + $dir.Name
				if(Test-Path $destinationDir){
					$dir2move = Get-ChildItem -Path $dir
					Write-Color 'Will move ', $dir2move, ' into ', $destinationDir -Color White, yellow, White, Green
					Move-Item $dir2move -Destination $destinationDir
				}
				else{
					Write-Color 'Will move ', $dir.Name, ' into ', $xDirs[$i] -Color White, yellow, White, Green
					if(!(Test-Path $xDirs[$i])){mkdir $xDirs[$i]}
					Move-Item $dir -Destination $xDirs[$i]
				}
			}
		}
	}
}

function DirectoryTree{
	$parentDirectories = @()
	foreach ($directory in Get-ChildItem -Recurse -Directory){
		Set-Location $directory
		$filesinside = Get-ChildItem
		if(($filesinside.Name -match 'pdf') -or ($filesinside.Name -match 'cbz') -or ($filesinside.Name -match 'jpg') -or ($filesinside.Name -match 'png'))
		{}
		else{
			$locationString = Get-Location
			$parentDirectories += '"' + $locationString + '"'
		}
	}
	$parentDirectories > 'F:\Library\Tree.txt'

}
function Capitalize{
	Set-Location 'F:\Library\Comic'
	foreach ($directory in Get-ChildItem -Recurse -Directory){
		Set-Location $directory
		[string[]]$renamerBL = @("*.xml","*.pdf","*.cbz","Folder.jpg","Folder.png", "folder.jpg", "folder.png")
		$capitalizeFiles = Get-ChildItem -Exclude "*.xml","*.pdf","*.cbz","Folder.jpg","Folder.png", "folder.jpg", "folder.png"
		foreach ($file in $capitalizeFiles){
			$file.FullName
			ReNamer.exe /silent /rename number $file
			Wait-Process -Name "ReNamer"
		}
	}
	<#Set-Location 'F:\Library\Graphic Novels\'
	foreach ($directory in Get-ChildItem -Directory){
		ReNamer.exe /silent /rename Capitalize $directory.FullName
		Wait-Process -Name "ReNamer"
	}#>
}

function findCrossovers{
	$seriesCollectionNames = @(
		"Amory Wars"
		"Batman"
		"Borderlands"
		"Brit"
		"Clive Barker"
		"Colder"
		"Constantine"
		"Critical Role"
		"Dark Ark"
		"Deadpool"
		"Dicks"
		"Ether"
		"Fables"
		"Grimm Fairy Tales"
		"Guardians of the Galaxy"
		"Gwenpool"
		"Hack Slash"
		"Harley Quinn"
		"Hellboy"
		"Hercules"
		"Joker"
		"Justice League"
		"Kick-Ass"
		"Lazarus"
		"Lobo"
		"Mad Max"
		"Midnighter"
		"Nailbiter"
		"Pilot Season"
		"Punisher"
		"Rumble"
		"Sonic"
		"Star Wars"
		"Suicide Squad"
		"The Boys"
		"The Last Zombie"
		"The Realm"
		"The Walking Dead"
		"Thor"
		"Transformers"
		"Venom"
		"Vikings"
		"WWE"
		"Wolverine"
		"X-Men"
	)
	$seriesCollectionDirectories = @(
		"F:\Library\Graphic Novels\Comic\Amory Wars"
		"F:\Library\Graphic Novels\Comic\Batman"
		"F:\Library\Graphic Novels\Comic\Borderlands"
		"F:\Library\Graphic Novels\Comic\Brit"
		"F:\Library\Graphic Novels\Comic\Clive Barker"
		"F:\Library\Graphic Novels\Comic\Colder"
		"F:\Library\Graphic Novels\Comic\Constantine"
		"F:\Library\Graphic Novels\Comic\Critical Role"
		"F:\Library\Graphic Novels\Comic\Dark Ark"
		"F:\Library\Graphic Novels\Comic\Deadpool"
		"F:\Library\Graphic Novels\Comic\Dicks"
		"F:\Library\Graphic Novels\Comic\Ether"
		"F:\Library\Graphic Novels\Comic\Fables"
		"F:\Library\Graphic Novels\Comic\Grimm Fairy Tales"
		"F:\Library\Graphic Novels\Comic\Guardians of the Galaxy"
		"F:\Library\Graphic Novels\Comic\Gwenpool"
		"F:\Library\Graphic Novels\Comic\Hack Slash"
		"F:\Library\Graphic Novels\Comic\Harley Quinn"
		"F:\Library\Graphic Novels\Comic\Hellboy"
		"F:\Library\Graphic Novels\Comic\Hercules"
		"F:\Library\Graphic Novels\Comic\Joker"
		"F:\Library\Graphic Novels\Comic\Justice League"
		"F:\Library\Graphic Novels\Comic\Kick-Ass"
		"F:\Library\Graphic Novels\Comic\Lazarus"
		"F:\Library\Graphic Novels\Comic\Lobo"
		"F:\Library\Graphic Novels\Comic\Mad Max"
		"F:\Library\Graphic Novels\Comic\Midnighter"
		"F:\Library\Graphic Novels\Comic\Nailbiter"
		"F:\Library\Graphic Novels\Comic\Pilot Season"
		"F:\Library\Graphic Novels\Comic\Punisher"
		"F:\Library\Graphic Novels\Comic\Rumble"
		"F:\Library\Graphic Novels\Comic\Sonic"
		"F:\Library\Graphic Novels\Comic\Star Wars"
		"F:\Library\Graphic Novels\Comic\Suicide Squad"
		"F:\Library\Graphic Novels\Comic\The Boys"
		"F:\Library\Graphic Novels\Comic\The Last Zombie"
		"F:\Library\Graphic Novels\Comic\The Realm"
		"F:\Library\Graphic Novels\Comic\The Walking Dead"
		"F:\Library\Graphic Novels\Comic\Thor"
		"F:\Library\Graphic Novels\Comic\Transformers"
		"F:\Library\Graphic Novels\Comic\Venom"
		"F:\Library\Graphic Novels\Comic\Vikings"
		"F:\Library\Graphic Novels\Comic\WWE"
		"F:\Library\Graphic Novels\Comic\X-Men\Wolverine"
		"F:\Library\Graphic Novels\Comic\X-Men\X-Men"
	)
	for ($i=0; $i -lt $seriesCollectionDirectories.Count; $i++){
		set-location $seriesCollectionDirectories[$i]
		$files = Get-ChildItem -Recurse -File
		for($ii=0; $ii -lt $seriesCollectionNames.Count; $ii++){
			if (!($files.Name -match $seriesCollectionNames[$i])){
			}
			else {
				if($files.Name -match $seriesCollectionNames[$ii]){
					foreach ($file in $files){
						if ($seriesCollectionNames[$i] -eq $seriesCollectionNames[$ii]){}
						else{
							#Write-Host 'Comparing ' + $seriesCollectionNames[$ii] + ' in ' $seriesCollectionNames[$i]
							$file.Name
						}
					}
				}
			}
		}
	}
}

function newest{
	$dirs2Monitor = @(
		'F:\Library\Graphic Novels\Manga\Boku No Hero Academia\Boku No Hero Academia'
		'F:\Library\Graphic Novels\Manga\Boruto ~ Naruto Next Generations'
		'F:\Library\Graphic Novels\Manga\Detective Conan'
		'F:\Library\Graphic Novels\Manga\Dragon Ball Super'
		'F:\Library\Graphic Novels\Manga\My Father Became A Cute Vtuber Girl!'
		'F:\Library\Graphic Novels\Manga\Onepunch-Man'
		'F:\Library\Graphic Novels\Manga\Shaman King\Shaman King ~ The Super Star'
		'F:\Library\Graphic Novels\Manga\Boku No Hero Academia\Vigilante ~ Boku No Hero Academia Illegals'
		'F:\Library\Graphic Novels\Manga\Kaiju No. 8'
	)
	foreach ($dir in $dirs2Monitor){
		set-location $dir
		$directoryFiles = Get-ChildItem -File
		$lastFile = SortNaturally -strArray $directoryFiles.Name | Select-Object -last 1 #Get the last file
		$mangaName = $lastFile.Split(' - ')
		$mangaIssue = $mangaName[1].split('.')
		Write-Color 'The newest issue of ', $mangaName[0], ' is ', $mangaIssue[0] -Color White, Yellow, White, Blue
	}
	Write-Separator
}

function routine{
	fix2.ps1 3 'F:\Library\Graphic Novels\Comic'
	compress
		removeEmptyDirectory 
		Move-Directories
		foreach ($Location in $Locations){
			set-location $Location
			cleanNames 
			set-location $Location
			decimals
			set-location $Location
			pad
			set-location $Location
			removeEmptyDirectory
		}
		set-location $rootDirectory
		Get-ChildItem -Recurse -File  '*zip' | Rename-Item -NewName {[System.IO.Path]::ChangeExtension($_.Name, "cbz")} #Rename every zipped file into cbz
		
		foreach ($Location in $Locations){
			set-location $Location
			missingFiles
		}
		set-location
}

Write-Color '1) ', 'Variable task' -Color White, Yellow
Write-Color '2) ', 'Remove empty directories' -Color White, Yellow
Write-Color '3) ', 'Decompress' -Color White, Yellow
Write-Color '4) ', 'Compress' -Color White, Yellow
Write-Color '5) ', 'Fix filenames' -Color White, Yellow
Write-Color '6) ', 'Find missing issues' -Color White, Yellow
Write-Color '7) ', 'Routine' -Color White, Yellow
Write-Color '8) ', 'Print the newest manga for special list' -Color White, Yellow
Write-Color '9) ', 'Directory Tree' -Color White, Yellow
Write-Separator
$selection = Read-Host
Write-Separator


switch ($selection)
{
	'1' {findCrossovers}
	'2' {removeEmptyDirectory}
	'3' {decompress}
	'4' {compress}
	'5' {
			OnePiece
			set-location $rootDirectory
			decimals
			set-location $rootDirectory
			cleanNames 
			set-location $rootDirectory
			cleanNames 
			set-location $rootDirectory
			pad
		}
	'6' {missingFiles}
	'7' {routine}
	'8'{newest}
	'9'{DirectoryTree}
}