[Question]
  [
I love BATCH, despite its shocking lack of functional commands, despite even due to its lack of non-integer support. Why? Because this works:
```
SET var=SET
%var% i=0
```
This would evaluate to:
```
SET var=SET
SET i=0
```
Fantastic, isn't it? I've used this technique in a [BATCH program](https://codegolf.stackexchange.com/questions/63772/determine-the-color-of-a-chess-square/63980#63980) before, because it saves bytes!
Your challenge, should you accept it, would be to "golf" BATCH programs in this way. You are to decrease the byte size of an input BATCH program by including `SET` statements that would evaluate to portions of the program, and in no other way modify the program. (This disallows, say, renaming a variable name to something shorter. Keep in mind that BATCH, asides from variables, is case insensitive.) Your score is calculated as thus:
```
score = # of characters in your program + 5*(net result bytes in test cases below)
```
I reserve the right to add more test cases, so as to discourage working to optimize the program for the test cases.
For the sake of this challenge, your `SET` statements cannot contain control characters (`|`, `<`, `>`, `%`) or linebreaks. You may not modify the code other than to move pieces of code inside a set statement. (That is, you may not remove unnecessary whitespace, replace `EQU` with `==`, etc.) We will assume that the lines end with `\n`.
## Test cases
Each test case is in a separate code block, and each test case is self-contained, meaning you should golf only assuming what's given within it. (I.e., if you `SET d=SET` in one program, that statement will not be automatically given to any other program). Each example result can be found after each test case. There is a line between test cases.
```
@ECHO OFF
SET increment=10
:loop
IF %increment% EQU 0 GOTO end
ECHO %increment%
SET /A %increment%-=1
GOTO loop
:end
EXIT
```
---
```
@ECHO OFF
SET /p INPUT=Enter input here:
SET R=%1
ECHO Last char of input here: %R:~-1%
```
---
```
@ECHO OFF
SET increment=10
:e
GOTO f
ECHO f
:f
GOTO g
ECHO g
:g
GOTO h
ECHO h
:h
GOTO i
ECHO i
:i
GOTO j
ECHO j
:j
IF 3==4 ( ECHO 4 ) ELSE ( ECHO 5 )
IF 5==3 ( GOTO l ) ELSE ( GOTO k )
:k
ECHO Done.
ECHO BATCH OUT!!
EXIT
:l
GOTO g
```
---
```
ECHO Hello, Hello, Hello, hello, hello, Hello, Hello!, hello, ello!, Lello.
```
---
Example outputs:
```
@ECHO OFF
SET increment=10
:loop
IF %increment% EQU 0 GOTO end
ECHO %increment%
SET /A %increment%-=1
GOTO loop
:end
EXIT
```
 (0 bytes saved)  
  
```
@ECHO OFF
SET %i%= input here:
SET /p INPUT=Enter%i%
SET R=%1
ECHO Last char of %i%%R:~-1%
```
 (3 bytes gained)  
  
```
@ECHO OFF
SET increment=10
SET g=GOTO 
SET e=ECHO 
:e
%g%f
%e%f
:f
%g%g
%e%g
:g
%g%h
%e%h
:h
%g%i
%e%i
:i
%g%j
%e%j
:j
IF 3==4 ( %e%4 ) ELSE ( %e%5 )
IF 5==3 ( %g%l ) ELSE ( %g%k )
:k
%e%Done.
%e%BATCH OUT!!
EXIT
:l
%g%g
```
 (10 chars saved)  
  
```
SET %h%=ello,
ECHO H%h% H%h% H%h% h%h% h%h% H%h% Hello!, h%h% ello!, Lello.
```
 (1 character saved)
  
[Answer]
# [Java 8, Java 10](http://openjdk.java.net/), ~~3884~~ 799/795 program + 484 output = ~~4368~~ 1283/1279 total
There are two limitations of this code:
* It assumes that variables from A to Z are free. (uppercase)
* It assumes that there are no more than 27 substitutions.
* Oh, and because Scanner doesn't quite cut it, empty input dumps out stacktrace.
But hey - there is a pro!
* Outputs best code. Always.
The code manages to perform better than examples provided by challenge author.
This golfed version has been made by [Kevin](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen).
## Java 8
```
c->{List<String>S=new Stack();HashMap<String,Integer>h=new HashMap(),s=new HashMap();int v=65,l=c.length(),b,e;do{for(b=0,l=c.length(),s.clear();b!=l;b++)for(e=b;++e<=l;)S.add(c.substring(b,e));S.removeIf(t->t.length()<5|t.matches(".*[\n|<%>].*"));S.forEach(t->h.merge(t,1,Integer::sum));S.clear();h.entrySet().removeIf(t->t.getValue()==1);String Y=c;int L=l;char V=(char)v;h.forEach((k,x)->{String i=Y,t;for(int j,I,q;i.contains(k);i=t+"%"+V+"%"+i.substring(j+k.length(),i.length())){for(I=-1,t=i.substring(q=0,j=i.indexOf(k));(I=t.indexOf("%",++I))>=0;q++);if(q%2>0)return;}i="SET "+V+"="+k+"\n"+i;if(i.length()<L)s.put(i,L-i.length());});h.clear();v++;c=s.isEmpty()?c:s.entrySet().stream().max((x,y)->x.getValue()>y.getValue()?1:-1).get().getKey();}while(l>c.length());return c;}
```
**[Try it online!](https://tio.run/##pVRdj9o4FH3Pr/BEGsmeBBfaslJjTLcfzA5aWh6go@12@mCMQwyJwyQOBU357bM3McwwK1WV2hfje3zPvcfHuSzFRrSW89W9ztZ5YdESYlpZndILhp49Q0HnFbI5solCs51VLZlXxnoyFWWJPght7jyEtLGqiIVU6GMdIjSxhTYLFOPDRhIG@N6DpbTCaok@IoM4upet/t1Il7bnEvsTbtQ3oAu5woRdiTL5INaHw3AIbRaq6CdN0uEQk7B8GjOQgzb8j26YcklTZRY2gaxZqNg8v4vzAs94@@lZSWWqRAHc2RlP2SwISJ2n@IwFgeoBRCZUzOdY0rKalY0cDAUJYRNaqCzfqGGMbatvH2r2ut8tzYSViSqxTy@@3JjvvfP@V3rhNyyoPxAyqUkJzVSxUNiGneMdo6issibvKCyhythiN1EWk/@1XCh7LdJKYcJ5BzjO889cNk6MQL1MRIGuOa5/yQZqHbvjVbgl8AYHjuafQ8vqq9fMZTgMb5mmMjcWXrrEK/CW28A/94PrZtUndiyD1aOh@mFLSGP5kLc6oeWnhFt4hSUg2szVdhxDdcIgzz4A0CEMgiEhfd5mt/AmTMf49vx5v00KZavCsL3m/mQwRY0e7gerwL8xIKtOfJTQG5GSriuLdThqnShj@9rWo8GbIGCSl1SXg2xtd5i8llF5ajrIViKDTSa2GG/DHRi3PTG/vzsJXneiVofUAG7WvxVUZPtviU4VTvvyRIW7C5Jsf8/qCVlXsxQm5DAom1zPUQb2H2bpy1ckyJMp0wbuBsPUTI4UxqgCT3alVRk4SWhVqvcq1ZmGGcX@zc2/PqFGbUEXc1Vcal5ZuoZ6NjXYf6vgzVSEnEjuo8B1OVH9I@6PT5oKv0L0Wz588WslLO62f9761Bs4PphD458J8N/EYNGTSzv6b93alTj8/@3v/xy8uxqj8eWlV3@32kgYZfjGeKftRcr7azwdo9hrcmIvih2wcMDCixYOSByQeFHiAO0A7UXaAUsHLL1o6Q0v0QvOXyKMGuwlImgwmgyOcReROqXL@QuAGnb6mNLEK0iJVq7k@9wo6rZv30zfXaHxp@nZmTf4Zzj1ovQg@D8 "Java (JDK) – Try It Online")**
## Java 10
```
c->{var S=new Stack<String>();HashMap<String,Integer>h=new HashMap(),s=new HashMap();int v=65,l=c.length(),b,e;do{for(b=0,l=c.length(),s.clear();b!=l;b++)for(e=b;++e<=l;)S.add(c.substring(b,e));S.removeIf(t->t.length()<5|t.matches(".*[\n|<%>].*"));S.forEach(t->h.merge(t,1,(x,y)->x+y));S.clear();h.entrySet().removeIf(t->t.getValue()==1);var Y=c;int L=l;var V=(char)v;h.forEach((k,x)->{String i=Y,t;for(int j,I,q;i.contains(k);i=t+"%"+V+"%"+i.substring(j+k.length(),i.length())){for(I=-1,t=i.substring(q=0,j=i.indexOf(k));(I=t.indexOf("%",++I))>=0;q++);if(q%2>0)return;}i="SET "+V+"="+k+"\n"+i;if(i.length()<L)s.put(i,L-i.length());});h.clear();v++;c=s.isEmpty()?c:s.entrySet().stream().max((x,y)->x.getValue()>y.getValue()?1:-1).get().getKey();}while(l>c.length());return c;}
```
**[Try it online!](https://tio.run/##pVRdb9s2FH3Xr2AEBCAjibXbesBEU10/nMVYWj/YC9Y1faBpyqIsUY5EuzZS//bsSrITZUBRYHsheA/vPffwUFep2IogXawedL4uSotSiOnG6oxeMPTiBfL6vyJbIJsoNN9bFchiY6wjM1FV6KPQ5t5BSBurylhIhT7VIUJTW2qzRDE@biRhgB8cWCorrJboEzKIowcZRPdbUaIpN@oblAm5GrY1ESbsSlTJR7E@Iv4Y2ixVGSVN8vEQE796HjOQg7b8l4GfcUkzZZY2gay5r9iiuI@LEs957/lZRWWmRAm18zOesbnnkTpP8TnzPDUEiEypWCywpNVmXjVyMBASwqa0VHmxVeMY2yCyj5zDwXdLc2Floirs0osvt@b78Dz6Si/cpgr4R0ImdVFCc1UuFbZ@38c7f0@CaOftm6yTrIQqY8v9VFlM/tVwqeyNyDYKE877hNVufuayMeEahNfxDccyESXZAs@pL175O2h0f3whzT/7ltWXrgtTf@zfMU1lYSy8cYVX4Cq3nnvuejfNqjtGpN7qyUr9uCWkMXvMg75vebfgDvxPAdFmoXaTGNgJgzz7CEAH3/PGhES8x@7gNZiO8d35y6hHSmU3pWEHzd3paIYaPdz1Vp57a0BWnfgkYXhNKrreWKz966CjjB1qS0/mbj2PSV5RXY3ytd1j8kaGVddwkK1EDptc7PDphTrGR/tO8KYfBn1SA7hZ/1DAyA7fEp0pnEWyo6K9C5Ls8MDq2Vhv5hnMxnFEtoVeoBzsP07Rl69IkGfzpQ3cDcaomR0pjFElnu4rq3JwktBNpT6oTOcaphO7t7d/u4QatQNdrGVpU4uNpWvgs5nB7jsFb6ZC1IrkLvLaLh3VP6r98UnD8F8K3cCFr32thMWD3s9bd72B46M5NP6ZAPdtDBY9u3Rb/r9u3VIc/3yHh99G768maHJ56dTfrTYSxhi@Md7vOaFyfp/MJih2mpzYCeMWWLbA0gmXLZC0QOKESQvoFtBOqFsgbYHUCVNnfIlecf4aYdRgrxFBo@vp6BQPEKlTBpy/Aqipzp5SmngFKeGqpfxQGEXb7bu3s/dXaPLn7OzMGf01njlhdhT8Dw "Java (JDK) – Try It Online")**.
# Original version
It's not golfed at all, I just wanted to have some fun, not to suffer. If you, dear reader, would like to golf this answer, please do it.
```
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Predicate;
public class Main {
	List<String> substrings = new ArrayList<String>();
	HashMap<String, Integer> hm = new HashMap<String, Integer>();
	HashMap<String, Integer> scores = new HashMap<String, Integer>();
	
	private int v1 = 65;
	
	public static String rfos(String inputString, String stringToReplace,
	        String stringToReplaceWith) {
	    int length = stringToReplace.length();
	    int inputLength = inputString.length();
	    int startingIndexofTheStringToReplace = inputString.indexOf(stringToReplace);
	    if(count(inputString.substring(0, startingIndexofTheStringToReplace), "%") % 2 == 1)
	    	return null;
	    
	    String finalString = inputString.substring(0, startingIndexofTheStringToReplace) + stringToReplaceWith
	            + inputString.substring(startingIndexofTheStringToReplace + length, inputLength);
	    return finalString;
	}
	
	public static int count(String text, String find) {
        int index = 0, count = 0, length = find.length();
        while( (index = text.indexOf(find, index)) != -1 ) {                
                index += length; count++;
        }
        return count;
	}
	
	private String process(String program) {
		int begin = 0, end, il = program.length();
		
		scores.clear();
		
		while(begin != program.length()) {
			for(end = begin + 1; end < program.length() + 1; end++)
				substrings.add(program.substring(begin, end));
			begin++;
		}
		
		substrings.removeIf(new Predicate<String>() {
			@Override
			public boolean test(String arg0) {
				return arg0.length() <= 4 || arg0.contains("\n")
						|| arg0.contains("|")
						|| arg0.contains("<")
						|| arg0.contains("%")
						|| arg0.contains(">");
			}
		});
		
		substrings.forEach(new Consumer<String>() {
			@Override
			public void accept(String t) {
				if(hm.containsKey(t)) {
					hm.replace(t, hm.get(t) + 1);
				} else {
					hm.put(t, 1);
				}
			}
			
		});
		
		substrings.clear();
		
		hm.entrySet().removeIf(new Predicate<Map.Entry<String, Integer>>() {
			@Override
			public boolean test(Map.Entry<String, Integer> t) {
				return t.getValue() == 1;
			}
			
		});
		
		hm.forEach(new BiConsumer<String, Integer>() {
			
			@Override
			public void accept(String arg0, Integer arg1) {
				String iteration = program;
				boolean between = false;
				while(iteration.contains(arg0)) {
					iteration = rfos(iteration, arg0, "%" + Character.toString((char) v1) + "%");
					if(iteration == null)
						return;
				}
				iteration = "SET " + Character.toString((char) v1) + "=" + arg0 + "\n" + iteration;
				if(iteration.length() < program.length())
					scores.put(iteration, program.length() - iteration.length());
			}
			
		});
		
		hm.clear();
		v1++;
		
		if(scores.isEmpty())
			return program;
		else
			return scores.entrySet().stream().max((entry1, entry2) -> entry1.getValue() > entry2.getValue() ? 1 : -1).get().getKey();
	}
	public static void main(String[] args) {
		Main processor = new Main();
		int genid = 0, before = 0, after = 0;
		String currentCode = new Scanner(System.in).useDelimiter("\\Z").next();
		
		System.out.println("Calculating first generation...");
		
		do {
			String cc = processor.process(currentCode);
			before = currentCode.length();
			after = cc.length();
			
			currentCode = cc;
			
			if(before > after) {
				System.out.println("Generation " + genid++);
				System.out.println(before + " -> " + after);
				System.out.println("***\n" + cc + "\n***");
			} else {
				System.out.println("Generation FAIL " + genid++);
				System.out.println(before + " -> " + after);
				System.out.println("***\n" + cc + "\n***");
			}
		} while(before > after);
		
		
	}
}
```
Example output:
```
SET B=GOTO 
SET A=ECHO 
@%A%OFF
SET increment=10
:e
%B%f
%A%f
:f
%B%g
%A%g
:g
%B%h
%A%h
:h
%B%i
%A%i
:i
%B%j
%A%j
:j
IF 3==4 ( %A%4 ) ELSE ( %A%5 )
IF 5==3 ( %B%l ) ELSE ( %B%k )
:k
%A%Done.
%A%BATCH OUT!!
EXIT
:l
%B%g
```
[**Try it online!**](https://tio.run/##xVdbb9s2FH6WfgVjoIBUu0Kdpnuwo6xt6rRBU3iYvQu27oGRKVupTBkU5SZY89uzc3hISb6l7dMCNKHOjd@5szd8zZ8VKyFvZp8fHrLlqlCa3QAxqnSWR6@V4ndXWamH/g7vPS8XH/lqD@eAwn7hScKlFGoPJ61korNCRm@y80KW1fJxqe@R@UWJWZZwLYa@v6qu8yxhSc7Lkn3kmWT/@h5CP51olcn5GSur69IcSxYzKb6wOhxOJAiHvmcDYWk9dim1mAt1xhZLq3dI4nH1MimUKL/HhO@tVLYGt1gmNVv3Qeenl0QnJ0vNNfwhZabSogzsOZOrSjujlkZOT4tfxSrniej5HrM/@wX@yPQihOiRHELIhZzrBcDYkoyIYUA7WYPgyim08LSEG2nwRGlgXsqZuC3S6UJMNq/YspGh3DgNtoA0NtMgKSqpg7ZSnfjgee/bN4Y91nnSCdkTdszimPVDsuwpoSslmazy3LpLv20Q00zy3J43Mf/g9ay7LyFN0vCne@CCb4eza5PZayeqDp/1seULcu53Sw9zR4G2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